Vapor `client.get`, transform and return json

若如初见. 提交于 2019-12-24 09:38:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!