JetForMe
(Rick M)
1
I have a schema with User, Organization, and UserOrganization pivot table. I want my /users/current endpoint to return a UserDTO with the user’s organizations filled out. I'm trying to do it like this:
func getCurrentUser(_ req: Request) throws -> EventLoopFuture<UserDTO> {
let userID = try req.auth.userID()
return req.users
.find(id: userID)
.unwrap(or: AuthenticationError.userNotFound)
.map
{ inUser in
return inUser.$organizations.get(reload: true, on: req.db)
.map
{ inOrgs in
UserDTO(from: inUser, organizations: inOrgs.organizations.map { OrganizationContent(from: $0) })
}
}
}
But the compiler complains about the middle map: Cannot invoke 'map' with an argument list of type '(@escaping (_) -> _)'
I don't want to eager-load the orgs in req.users.find(id:), because they're not always necessary. I've tried a few ways with both get() and load(), but I can't seem to figure out the right way to write this.
JetForMe
(Rick M)
2
Ah, I finally figured it out (Thanks to Mads on Discord):
func getCurrentUser(_ req: Request) throws -> EventLoopFuture<UserDTO> {
let userID = try req.auth.userID()
return req.users
.find(id: userID)
.unwrap(or: AuthenticationError.userNotFound)
.flatMap
{ inUser in
return inUser.$organizations.get(on: req.db)
.map
{ inOrgs in
UserDTO(from: inUser, organizations: inOrgs.map { OrganizationContent(from: $0) })
}
}
}
Now I'm trying to understand if that can be written in chained fashion, to avoid nesting closures.