蒸汽将数据从 postgres 传递到叶模板

Vapor pass data from postgres to a leaf template

我是 Vapor 新手,

我尝试将数据从 postgres 传递到 leaf

routes.swift中我有渲染叶子模板的函数:

func routes(_ app: Application) throws {
    app.get("all") { req -> EventloopFuture<View> in
        let todos = Todo.query(on: req.db).all()

        let context = TodoContext(todos: todos)

        return req.view.render("index", context)
    }
}

但是我从上下文行中得到一个错误,它说 无法将类型 'EventLoopFuture<[Todo]>' 的值转换为预期的参数类型“[Todo]”。

如何将 EventLoopF​​uture<[Todo]> 转换为“[Todo]”以便我可以在上下文中使用它? 我在查询 .all() 之后尝试了 map 函数,但在此之后它仍然是一个 EventLoopF​​uture<[Todo]>.

TodoContext:

struct TodoContext: Content {
    let todos: [Todos]
}

Todo 模型:

final class Todo: Model, Content {
    static let schema = "todo"
    
    @ID(key: .id)
    var id: UUID?

    @Field(key: "todo")
    var todo: String

    @Field(key: "complete")
    var complete: Bool

    init() { }

    init(id: UUID? = nil, todo: string, complete: Bool) {
        self.id = id
        self.todo = todo
        self.complete = complete
    }
}

你是对的,你需要处理未来,但你应该使用 flatMap 因为渲染调用 returns 未来。所以你的代码应该是这样的:

func routes(_ app: Application) throws {
    app.get("all") { req -> EventloopFuture<View> in
        return Todo.query(on: req.db).all().flatMap { todos in
          let context = TodoContext(todos: todos)
          return req.view.render("index", context)
      }
    }
}