【问题标题】:Correct way to load data from database and load it to the view in Vapor 3?从数据库加载数据并将其加载到 Vapor 3 中的视图的正确方法?
【发布时间】:2018-04-29 05:19:07
【问题描述】:

我有一个Vapor 3 项目,它可以上传一些格式为html 的内容字符串。并具有将此内容加载为html 页面的功能。代码如下:

func newpost(_ reqest: Request) throws -> Future<View> {
    self.getContent(req: reqest) { (content) in
        return try reqest.view().render("newpost.leaf", content)
    }

}

func getContent(req:Request, callback: @escaping (String) -> ()) {
   let _ = BlogModel.query(on: req).first().map(to: BlogModel.self) { (blog) -> (BlogModel) in
        callback((blog?.content)!)
        return blog!
    }
}

但是这段代码会导致错误:

从 '(_) throws -> _' 类型的抛出函数到非抛出函数类型 '(String) -> ()' 的无效转换

如果我尝试将return try reqest.view().render("newpost.leaf", content) 移出该块,那么我将无法获得content。请帮助我找到正确的加载方式。

【问题讨论】:

    标签: swift swift4.1 vapor


    【解决方案1】:

    您应该查看文档(Promises 等)中的 Async section。无需使用回调。

    这可能是从数据库获取数据并使用 Leaf 呈现数据的一种方法(这与您的代码的想法相同,但用 Promises 替换回调并清理不必要的代码):

    enum APIError: AbortError {
        case dataNotFound
    }
    
    /// Render the HTML string using Leaf
    func newPost(_ req: Request) throws -> Future<View> {
        return getContent(req)
            .flatMap(to: View.self) { model in
                // By default, Leaf will assume all templates have the "leaf" extension
                // There's no need to specify it
                return req.view().render("newpost", model)
            }
    }
    
    /// Retrieve X content from the DB
    private func getContent(_ req: Request) throws -> Future<BlogModel> {
        return BlogModel.query(on: req)
            .first() // can be nil
            .unwrap(or: APIError.dataNotFound)
            // returns an unwrapped value or throws if none
    }
    

    如果你不想在找不到数据时抛出,你可以使用 nil-coalescing 将 nil 转换为空字符串。

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多