Vapor 将数据从 postgres 传递到叶子模板

问题描述

我是 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)
    }
}

但是我从上下文行收到一个错误,它说无法将类型“EventLoopF​​uture”的值转换为预期的参数类型“[Todo]”。

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

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,因为渲染调用返回未来。所以你的代码应该是这样的:

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)
      }
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...