【问题标题】:Vapor pass data from postgres to a leaf template蒸汽从 postgres 传递数据到叶子模板
【发布时间】:2021-07-28 13:55:41
【问题描述】:

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

待办事项模型:

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

【问题讨论】:

    标签: swift postgresql vapor


    【解决方案1】:

    你是正确的,你需要处理未来,但你应该使用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)
          }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-05
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 2018-11-25
      相关资源
      最近更新 更多