在不使用apollo-runtime的情况下使用模型
apollo-runtime
和ApolloClient
提供了支持进行网络请求和与缓存交互,但您可以在没有运行时的情况下使用生成的模型和解析器,并使用您选择的网络层对HTTP调用进行操作。
为此,请删除com.apollographql.apollo3:apollo-runtime
依赖项,并替换为:
build.gradle
implementation("com.apollographql.apollo3:apollo-api:3.8.5")
构建HTTP请求体
要将HTTP POST请求体发送到您的服务器,请使用composeJsonRequest
:
/*** jsonRequest contains data to be sent to the server* {* "query": ...* "variables": ...* "extensions": ...* }*/val body = buildJsonString {query.composeJsonRequest(this, customScalarAdapters)}/*** Send it to your backend*/val httpResponse = sendHttpRequest("POST","https://com.example/graphql","application/json",body)
解析HTTP响应体
要将网络响应解析为类型安全的模型,请使用parseJsonResponse
:
/*** jsonResponse should contain a json with data and possibly errors:* {* "data": ...* "errors": ...* "extensions": ...* }**/val jsonReader = httpResponse.body.source().buffer().jsonReader()val response = operation.parseJsonResponse(jsonReader)println(response.data)
构建HTTP响应体
对于您的集成测试,您还可以从程序构建的data
中构建完整的响应。为此,请使用composeJsonResponse
:
/*** Build a fake data object**/val data = SomeQuery.Data(...)/*** jsonResponse contains a json with data and possibly errors:* {* "data": ...* "errors": ...* "extensions": ...* }**/val jsonResponse = buildJsonString {operation.composeJsonResponse(this, data)}mockServer.enqueue(jsonResponse)