Vapor `client.get`,转换和 return json

Vapor `client.get`, transform and return json

我正在尝试从另一个 Web 服务获取数据,然后对其进行转换并 return。我在文档中找到了一个 Spotify 示例,但我不确定如何 return 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
}

我在尝试构建时遇到此错误:error: return expression of type '[Polymorphic]?' does not conform to 'ResponseRepresentable'

您的 result.dataContent,可以是任何东西。您需要先确定它是JSON,然后才能return它。

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
}