问题
I’m trying to GET data from another web service, then transform it and return it. I found a Spotify example in the docs, but I’m not sure how to return a portion of the JSON.
drop.get("music") { request in
guard let query = request.data["q"]?.string else {
throw Abort.badRequest
}
let result = try drop.client.get(
"https://api.spotify.com/v1/search",
query: ["type": "artist", "q": query]
)
return result.data["artists"]?.array
}
I'm getting this error when I try to build: error: return expression of type '[Polymorphic]?' does not conform to 'ResponseRepresentable'
回答1:
Your result.data
is Content
, which could be anything. You need to first make sure it's JSON, and then you can return it.
drop.get("music") { request in
guard let query = request.data["q"]?.string else {
throw Abort.badRequest
}
let result = try drop.client.get(
"https://api.spotify.com/v1/search",
query: ["type": "artist", "q": query]
)
guard
result.status == .ok,
let artistsJson = result.data["artists"] as? JSON
else {
throw Abort.serverError
}
return artistsJson
}
来源:https://stackoverflow.com/questions/41868625/vapor-client-get-transform-and-return-json