Java/Kotlin/Android:graphql-kotlin(客户端)
graphql-github-io-zh-Hans生态项目与库
项目简介
GraphQL Kotlin 提供了一套轻量级的类型安全 GraphQL HTTP 客户端库。该库包含基于 Ktor HTTP 客户端和 Spring WebClient 的参考实现,同时允许开发者基于其他引擎进行自定义扩展。类型安全的数据模型由 GraphQL Kotlin Gradle 和 Maven 插件在构建时自动生成。
快速开始
要在项目中生成基于 Ktor 的 GraphQL 客户端,请在 Gradle 构建文件中添加以下配置:
kotlin
// build.gradle.kts
import com.expediagroup.graphql.plugin.generator.GraphQLClientType
import com.expediagroup.graphql.plugin.gradle.graphql
plugins {
id("com.expediagroup.graphql") version $latestGraphQLKotlinVersion
}
dependencies {
implementation("com.expediagroup:graphql-kotlin-ktor-client:$latestGraphQLKotlinVersion")
}
graphql {
client {
// 目标 GraphQL 端点
endpoint = "http://localhost:8080/graphql"
// 生成客户端代码的包名
packageName = "com.example.generated"
clientType = GraphQLClientType.KTOR
}
}
默认情况下,GraphQL Kotlin 插件会在 src/main/resources 目录下查找查询文件。假设有如下 helloWorld: String! 查询,我们可以在项目中添加一个 HelloWorldQuery.graphql 示例查询文件:
graphql
query HelloWorldQuery {
helloWorld
}
插件将生成以下客户端代码:
kotlin
package com.example.generated
import com.expediagroup.graphql.client.GraphQLKtorClient
import com.expediagroup.graphql.types.GraphQLResponse
import kotlin.String
const val HELLO_WORLD_QUERY: String = "query HelloWorldQuery {\n helloWorld\n}"
class HelloWorldQuery(
private val graphQLClient: GraphQLKtorClient<*>
) {
suspend fun execute(requestBuilder: HttpRequestBuilder.() -> Unit = {}): GraphQLResponse<HelloWorldQuery.Result> =
graphQLClient.execute(HELLO_WORLD_QUERY, "HelloWorldQuery", null, requestBuilder)
data class Result(
val helloWorld: String
)
}
执行客户端
生成客户端代码后,可以通过以下方式执行查询:
kotlin
package com.example.client
import com.expediagroup.graphql.client.GraphQLKtorClient
import com.expediagroup.graphql.generated.HelloWorldQuery
import kotlinx.coroutines.runBlocking
import java.net.URL
fun main() {
val client = GraphQLKtorClient(url = URL("http://localhost:8080/graphql"))
val helloWorldQuery = HelloWorldQuery(client)
runBlocking {
val result = helloWorldQuery.execute()
println("hello world query result: ${result.data?.helloWorld}")
}
client.close()
}
总结
graphql-kotlin 为 Kotlin 开发者提供了一套完整的 GraphQL 客户端解决方案:
- 支持 Ktor 和 Spring WebClient 两种主流 HTTP 引擎,且可通过自定义实现扩展其他引擎
- 通过 Gradle/Maven 插件 在构建阶段生成类型安全的客户端代码,减少手动维护的数据模型
- 生成的代码具备类型安全特性,查询结果映射为 Kotlin 数据类
- 基于协程提供挂起函数支持,与 Kotlin 异步编程模型完美融合
更多详细信息,请参阅 graphql-kotlin 官方文档。
帮助我们改进文档
发现翻译问题或内容错误?请告诉我们。
