vapor / fluent

Vapor ORM (queries, models, and relations) for NoSQL and SQL databases
https://docs.vapor.codes/4.0/fluent/overview/
MIT License
1.32k stars 172 forks source link

Hook in Model{,Token}Authenticatable to load associated information #700

Open tholo opened 4 years ago

tholo commented 4 years ago

It would often be very helpful if it would be possibly to hook into ModelAuthenticatable and ModelTokenAuthenticatable to cause related data to be eager loaded.

One area where this would be very useful would be if a User has a relationship to e.g. Role, which is then used to validate actual access to resources, for instance:

final class User: Model {
...
@Siblings(through: UserRole.self, from: \.$user, to: \.$role)
public var roles: [Role]
...
}

final class UserRole: Model { ... }

final class Role: Model {
...
@Siblings(through: UserRole.self, from: \.$role, to: \.$user)
public var users: [User]
...
}

With such a setup one would rather often want to be able to access User.roles to validate access to some resource, but with the current implementation of ModelAuthenticatable and ModelTokenAuthenticatable one has to load User.$roles in each and every instance one wants to check them.

Magiguigui commented 4 years ago

You can override the static query(on: Database) method of Model protocol directly in your User model :

    public static func query(on database: Database) -> QueryBuilder<User> {
        return QueryBuilder(database: database)
            .with(\.$roles)
    }