'Querying nested children in Vapor's Fluent

Env: Vapor/Fluent 4.0.0

I have a tree structured data with model like this:

final class Ingredient: Model {
    static let schema = "ingredients"

    @ID(key: "id")
    var id: UUID?
    
    @Field(key: "name")
    var name: String

    @OptionalParent(key: "parent_id")
    var parent: Ingredient?

    @Children(for: \.$parent)
    var children: [Ingredient]
}

And I want to return the whole tree as a JSON in one of API methods.

func index(req: Request) throws -> EventLoopFuture<[APIIngredient]> {
        // Gathering top-level nodes without parents
        let ingredients = try Ingredient.query(on: req.db)
            .filter(\.$parent.$id == nil)
            .sort(\.$name)
            .all()
            .wait()
    enter code here
        // Creating API models
        let apiIngredients = try ingredients.map {
            try APIIngredient(
                ingredient: $0,
                childrenGetter: {
                    try $0.$children.query(on: req.db).all().wait()
                }
            )
        }

        return req.eventLoop.future(apiIngredients)
    }

But I've found that .wait() is disallowed to use in request handlers. What's the right way to approach this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source