过滤数据 从 vapor 客户端获取
Filter data From vapor client get
我正在使用 vapor 的客户端获取 get 请求。
func sendGetRequest(req: Request) throws -> Future<Response> {
let client = try req.make(FoundationClient.self)
return client.get("http://example.vapor.codes/json", headers: ["Accept-Language" : "ar"])
.map(to: Response.self, { clientResponse in
let response = req.makeResponse()
response.http.status = clientResponse.http.status
response.http.body = clientResponse.http.body
return response
})
}
这个 return 是所有 json 数据,我想将其过滤为 return 2 个属性,例如在这种情况下 (dict,number)
我已经为数据创建了一个模型
struct ExampleData: Codable {
// var array : [Int]
var dict : [String : String]
var number : Int
// var string : String
}
该函数期望我 return 一个 Future< Response>,但是如果我将其更改为 Future< ExampleData> 并将映射设置为 .map(to: ExampleData.self ..)
我得到
Cannot convert return expression of type 'Response' to return type
'TodoController.ExampleData'
我想通了
func sendGetRequest(req: Request) throws -> Future<ExampleData> {
let client = try req.make(Client.self)
let ans = client.get("http://example.vapor.codes/json", headers: ["Accept-Language" : "ar"]).flatMap { exampleResponse in
return try exampleResponse.content.decode(ExampleData.self)
}
return ans
}
我正在使用 vapor 的客户端获取 get 请求。
func sendGetRequest(req: Request) throws -> Future<Response> {
let client = try req.make(FoundationClient.self)
return client.get("http://example.vapor.codes/json", headers: ["Accept-Language" : "ar"])
.map(to: Response.self, { clientResponse in
let response = req.makeResponse()
response.http.status = clientResponse.http.status
response.http.body = clientResponse.http.body
return response
})
}
这个 return 是所有 json 数据,我想将其过滤为 return 2 个属性,例如在这种情况下 (dict,number)
我已经为数据创建了一个模型
struct ExampleData: Codable {
// var array : [Int]
var dict : [String : String]
var number : Int
// var string : String
}
该函数期望我 return 一个 Future< Response>,但是如果我将其更改为 Future< ExampleData> 并将映射设置为 .map(to: ExampleData.self ..)
我得到
Cannot convert return expression of type 'Response' to return type 'TodoController.ExampleData'
我想通了
func sendGetRequest(req: Request) throws -> Future<ExampleData> {
let client = try req.make(Client.self)
let ans = client.get("http://example.vapor.codes/json", headers: ["Accept-Language" : "ar"]).flatMap { exampleResponse in
return try exampleResponse.content.decode(ExampleData.self)
}
return ans
}