@arrirpc/codegen-kotlin

中文文档
0.85.0发布于 2026/10/03MITTypeScriptESM + CJS近 30 天下载 4553
原始使用文档
文档目录8 节
  1. Setup
  2. 1) Add the generator to your arri config
  3. 2) Install dependencies
  4. Using the Generated Code
  5. Initialize the client
  6. Calling Procedures
  7. Using Arri Models
  8. Development

Arri Kotlin Codegen

Setup

1) Add the generator to your arri config

// arri.config.ts
import { defineConfig, generators } from 'arri';

export default defineConfig({
    generators: [
        generators.kotlinClient({
            clientName: 'MyClient',
            outputFile: './client/src/MyClient.g.kt',
        }),
    ],
});

Options:

NameDescription
outputFile (required)Path to the file that will be created by the generator
clientNameThe name of the generated client class (Defaults to "Client")
typePrefixAdd a prefix to the generated class names
rootServiceThe root service of the generated client

2) Install dependencies

The generated code relies on the following dependencies:

Using the Generated Code

Initialize the client

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()
    }
}

The root client will be a class containing all of the services and procedures in a single class. If you only need a particular service, you can initialize just that service.

val service = MyClientUsersService(
        httpClient = httpClient,
        baseUrl = "https://example.com",
        headers = {
            mutableMapOf(Pair("x-example-header", "<some-header-value>"))
        }
    )

Client / Service Options

NameTypeDescription
httpClientHttpClientAn instance of ktor HttpClient
baseUrlStringThe base URL of the API server
headers(() -> MutableMap<String, String>?)?A function that returns a map of http headers
onError (Optional)((err: Exception) -> Unit)A hook that fires whenever any exception is thrown by the client

Calling Procedures

Standard HTTP Procedures

runBlocking {
    // procedure with no parameters
    val getUsersResponse = myClient.users.getUsers()

    // procedure with parameters
    val getUserResponse = myClient.users.getUser(GetUserParams(userId = "12345"))
}

Event Stream Procedures

Basic Usage
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")
        }
    )
}
Cancelling Requests

Event stream procedures can be cancelled from inside one of the hooks by throwing a CancellationException

runBlocking {
    myClient.users.watchUserChanges(
        onResponseError { err ->
            println("Server returned an error: ${err.code} ${err.message}")
            throw CancellationException()
        }
    )
}

You can also spawn a job and cancel that job in order to cancel the Event stream procedure from the outside

val job = someCoroutineScope.launch {
    myClient.users.watchUserChanges()
}
job.cancel()
Other Options
OptionTypeDescription
bufferCapacityIntMax buffer size that can be allocated towards reading messages received. Default is 1024 * 1024 (1MB).
maxBackoffTimeLong?Max wait time between retries in milliseconds. Default is 30000ms

Using Arri Models

All generated models will be data classes. They will have access to the following features:

Methods:

  • toJson(): String
  • toUrlQueryParams(): String

Factory Methods:

  • new()
  • fromJson(input: String)
  • fromJsonElement(input: JsonElement, instancePath: String)

Other Notes

  • All Enums will have a serialValue property.
  • Discriminator schemas are converted to sealed classes

Development

# build the library
pnpm nx build codegen-kotlin

# test
pnpm nx test codegen-kotlin

# lint
pnpm nx lint codegen-lint

版本与发布记录

@arrirpc/codegen-kotlin 共发布 91 个版本,首次发布于 2024/05/14;过去 12 个月发布了 11 个版本。

版本发布日期距今
0.85.0latest2026/10/031 个月前
0.84.12026/08/043 个月前
0.84.02026/08/043 个月前
0.83.12026/07/143 个月前
0.83.02026/07/143 个月前
0.82.02026/05/225 个月前

其他发布通道:beta → 0.76.3-beta.0。

关于 @arrirpc/codegen-kotlin 的常见问题

如何安装 @arrirpc/codegen-kotlin?

在项目目录运行 npm install @arrirpc/codegen-kotlin,或使用 pnpm add / yarn add / bun add。

@arrirpc/codegen-kotlin 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@arrirpc/codegen-kotlin 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@arrirpc/codegen-kotlin 可以商用吗?

@arrirpc/codegen-kotlin 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@arrirpc/codegen-kotlin 的下载量有多少?

根据 npm 官方下载统计,@arrirpc/codegen-kotlin 在 2026/10/07 – 2026/11/05 这 30 天内被下载 4,553 次,日均约 152 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@arrirpc/codegen-kotlin 还在维护吗?

最新版本 0.85.0 发布于 2026/10/03(1 个月前);至今共发布 91 个版本,其中过去 12 个月发布了 11 个;首次发布于 2024/05/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。