阿里·克特林 代码
设置
1) 将生成器添加到您的 arri 配置
// arri.config.ts
import { defineConfig, generators } from 'arri';
export default defineConfig({
generators: [
generators.kotlinClient({
clientName: 'MyClient',
outputFile: './client/src/MyClient.g.kt',
}),
],
});
选项 :
| 名称 | 说明 |
|---|---|
| 输出文件( 需要) | 由生成器创建的文件路径 |
| 客户端Name | 生成客户端类的名称( 默认为“ 客户端 ” ) |
| 类型 前缀 | 在生成的类名中添加前缀 |
| 根服务 | 生成客户端的根服务 |
(2) 安装依赖关系
生成的代码依赖于下列依赖性:
使用生成代码
初始化客户端
fun main() {
// create a Ktor HTTP client
val httpClient = HttpClient() {
install(HttpTimeout)
}
// initialize your generated client and pass it the httpClient
// the client name will match whatever options you passed into your arri config
val client = MyClient(
httpClient = httpClient,
baseUrl = "https://example.com",
// a function that returns a mutable map of headers
// this function will run before every request. Or before every reconnection in the case of SSE
headers = {
mutableMapOf(Pair("x-example-header", "<some-header-value>"))
}
)
runBlocking {
client.someProcedure()
}
}
Root客户端将是一个包含单一类中所有服务和程序的类. 如果您只需要特定的服务,您可以初始化该服务.
val service = MyClientUsersService(
httpClient = httpClient,
baseUrl = "https://example.com",
headers = {
mutableMapOf(Pair("x-example-header", "<some-header-value>"))
}
)
客户端/ 服务选项
| 名称 | 类型 | 说明 |
|---|---|---|
| httpclient 语句 | HttpClient | Kttpclient 实例 |
| 基数Url | String | API 服务器的基础 URL |
| 页眉 | (() -> MutableMap<String, String>?)? | 返回 http headers 地图的函数 |
| 错误( 可选) | ((err: Exception) -> Unit) | 当客户提出例外时,会起火的钩子 |
呼叫程序
标准HTTP程序
runBlocking {
// procedure with no parameters
val getUsersResponse = myClient.users.getUsers()
// procedure with parameters
val getUserResponse = myClient.users.getUser(GetUserParams(userId = "12345"))
}
事件流程序
基本用途
runBlocking {
myClient.users.watchUserChanges(
onData { message ->
println("New message: ${message}")
},
onOpen {
println("Connection established")
}
onRequestError { err ->
println("Error connecting to server: ${err}")
},
onResponseError { err ->
println("Server returned an error: ${err.code} ${err.message}")
},
onClose {
println("Connection closed")
}
)
}
取消请求
事件流程序可以通过扔出一个 CancellationException
runBlocking {
myClient.users.watchUserChanges(
onResponseError { err ->
println("Server returned an error: ${err.code} ${err.message}")
throw CancellationException()
}
)
}
您也可以生产工作并取消该工作,以便从外部取消事件流程序
val job = someCoroutineScope.launch {
myClient.users.watchUserChanges()
}
job.cancel()
其他选项
| 选项 | 类型 | 说明 |
|---|---|---|
| 缓冲能力 | 内 | 最大缓冲大小, 用于读取收到的信件 。 默认为1024 * 1024 (1MB). |
| 最大备份时间 | 长? | Max 等待时间在毫秒内重复 默认为 3000 ms |
使用Arri模型
所有生成的模型都将是数据类. 他们将获得以下特征:
方法数字 :
toJson(): StringtoUrlQueryParams(): String
工厂方法数字 :
new()fromJson(input: String)fromJsonElement(input: JsonElement, instancePath: String)
其他说明
- 所有Enums将有一个
serialValue属性. - 歧视者计划转换为密封类
发展
# build the library
pnpm nx build codegen-kotlin
# test
pnpm nx test codegen-kotlin
# lint
pnpm nx lint codegen-lint