【问题标题】:Vapor 3 API: embed Future<Model> in response objectVapor 3 API:在响应对象中嵌入 Future<Model>
【发布时间】:2019-03-26 00:42:06
【问题描述】:

假设我有一个名为Estimate 的模型。我有一个 Vapor 3 API,我想返回这些模型的列表,按查询参数过滤。这样做当前会返回一个Future&lt;[Estimate]&gt;,这会导致 API 返回如下所示的 JSON:

[{estimate object}, {estimate object}, ...]

相反,我想让它返回以下内容:

{"estimates": [{estimate object}, {estimate object}, ...]}

所以,和以前一样,但是包装在一个带有单个键 "estimates" 的 JSON 对象中。

According to the documentation,任何时候我想返回一些非默认的东西,我都应该为它创建一个新的类型;这对我来说建议我应该创建一个像这样的类型:

final class EstimatesResponse: Codable {
  var estimates: [Estimate]?
}

但是,过滤后我得到一个 Future&lt;[Estimate]&gt; 而不是纯 [Estimate] 数组,这意味着我无法将它分配给我的 EstimatesResponse estimates 属性。将estimates 的类型设为Future&lt;[Estimate]&gt; 似乎很奇怪,我不确定结果如何。

那么,我怎样才能返回正确格式的 JSON?

【问题讨论】:

    标签: swift vapor


    【解决方案1】:

    首先,您需要创建 Codable 对象,我更喜欢下面的 struct。必须为路由实现协议Content

    struct EstimatesResponse: Codable {
      var estimates: [Estimate]
     }
    
     extension EstimatesResponse: Content { } 
    

    我假设您使用的是控制器,并且在控制器内部,您可以使用以下伪代码。调整您的代码,使 valFuture,然后使用 flatmap/map 获得 [Estimate]强>。

    func  getEstimates(_ req: Request) throws -> Future<EstimatesResponse> {
            let val = Estimate.query(on: req).all()
            return val.flatMap { model in
                let all = EstimatesResponse(estimates: model)
                return Future.map(on: req) {return all }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2019-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      相关资源
      最近更新 更多