2

i'm using vapor's client to fetch a get request.

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

this returns all the json data , i want to filter it to just return 2 attributes, for example in this case (dict,number)

i've created a model for the data

struct ExampleData: Codable {
  //  var array : [Int]
    var dict : [String : String]
    var number : Int
 //   var string : String
}

the function expects me to return a Future< Response>, but if i change it to Future< ExampleData> and set the mapping to .map(to: ExampleData.self ..)

i get

Cannot convert return expression of type 'Response' to return type 'TodoController.ExampleData'

Tarek hemdan
  • 874
  • 2
  • 10
  • 24
  • May be a silly question, but are you still returning the `Response` object you created inside of your `.map(to: ExampleData.self...`? Or did you change that to return an `ExampleData` struct? – ssrobbi Jun 16 '18 at 03:32
  • @ssrobbi the return is of type ExampleData – Tarek hemdan Jun 16 '18 at 09:38

1 Answers1

2

i figured it out

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
}
Tarek hemdan
  • 874
  • 2
  • 10
  • 24