Vapor 3 API:在响应对象中嵌入 Future<Model>

Vapor 3 API: embed Future<Model> in response object

假设我有一个名为 Estimate 的模型。我有一个 Vapor 3 API,我想 return 这些模型的列表,按查询参数过滤。目前这样做 returns a Future<[Estimate]>,结果 API returning JSON 看起来像这样:

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

相反,我想 return 是这样的:

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

所以,和以前一样,但是用一个键 "estimates" 包裹在一个 JSON 对象中。

According to the documentation,任何时候我想要 return 一些非默认的东西,我应该为它创建一个新类型;这向我建议我应该创建一个像这样的类型:

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

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

那我怎么才能returnJSON格式正确呢?

首先,你需要创建 Codable 对象,我更喜欢下面的结构。必须为路由实施协议 Content

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

 extension EstimatesResponse: Content { } 

我假设您使用的是控制器,在控制器内部,您可以使用以下伪代码。调整您的代码,使 valFuture<[Estimate]>,然后使用 flatmap/map 得到 [估计值]

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