修改kotlin中Swagger Codegen方法的contentHeaders

Modify contentHeaders of Swagger Codegen methods in kotlin

我正在为我的 REST API 调用使用 swagger codegen。出于身份验证目的,我需要在每个请求的 headers 中发送一个 session-token。目前这是通过 APIClients' defaultHeaders

完成的
open class ApiClient(val baseUrl: String) {
    companion object {
        ...
        @JvmStatic
        var defaultHeaders: Map<String, String> by ApplicationDelegates.setOnce(mapOf(ContentType to JsonMediaType, Accept to JsonMediaType))
        ...
    }
}

swagger生成代码的方式,这些headers只能修改一次

ApiClient.defaultHeaders += mapOf("Authorization" to userSession!!.idToken.jwtToken)

问题是,我无法更改令牌(例如,因为另一个用户在应用程序生命周期内登录)。深入查看生成的代码,在发送每个请求之前,正在合并 defaultHeadersrequestConfig.headers (=contentHeaders)。

inline protected fun <reified T: Any?> request(requestConfig: RequestConfig, body : Any? = null): ApiInfrastructureResponse<T?> {
    ...
    val headers = defaultHeaders + requestConfig.headers
    ...
}

给定的 RequestConfig object 来自每个 api 调用。但是,无法更改这些 contentHeaders。默认情况下它们也是空的。

fun someAPIRestCall(someParam: kotlin.String) : Unit {
    val localVariableBody: kotlin.Any? = type
    val localVariableQuery: MultiValueMap = mapOf()

    val contentHeaders: kotlin.collections.Map<kotlin.String,kotlin.String> = mapOf() // THESE WILL BE MERGED WITH defaultHeaders
    val acceptsHeaders: kotlin.collections.Map<kotlin.String,kotlin.String> = mapOf("Accept" to "application/json")
    val localVariableHeaders: kotlin.collections.MutableMap<kotlin.String,kotlin.String> = mutableMapOf()
    localVariableHeaders.putAll(contentHeaders)
    localVariableHeaders.putAll(acceptsHeaders)

    val localVariableConfig = RequestConfig(
        RequestMethod.POST,
        "someEndpointURL"),
        query = localVariableQuery,
        headers = localVariableHeaders // THESE WILL BE MERGED WITH defaultHeaders
    )
    val response = request<Unit>(
        localVariableConfig,
        localVariableBody
    )
    ...
}

是否可以告诉 swagger-codegen 在生成的方法签名中包含某种参数以向那些 contentHeaders 添加值?

编辑:

这是我的 gradle 构建链中的当前 code-gen 调用

task generateSwagger(type: JavaExec) {
    main = "-jar"
    args "swagger-codegen-cli-2.4.7.jar", "generate", "-i", "./swagger_core.yml", "-l", "kotlin", "-o", "./tmp/RestApi", "--type-mappings", "number=kotlin.Long"
}

到现在为止,我找到了一个解决方案,它更像是一个 hack,但它有效。

当我使用 gradle 构建应用程序时,我引入了一个任务,它会在实际编译之前更改生成的 swagger 代码。

task editAPISources {
    def token = "Map<String, String> by ApplicationDelegates.setOnce(mapOf(ContentType to JsonMediaType, Accept to JsonMediaType))"
    def value = "MutableMap<String, String> = mutableMapOf(ContentType to JsonMediaType, Accept to JsonMediaType)"
    def file = new File("./app/tmp/RestApi/src/main/kotlin/io/swagger/client/infrastructure/ApiClient.kt")
    def newConfig = file.text.replace(token, value)
    file.write newConfig
}

结果现在可以改变 header :=

@JvmStatic
var defaultHeaders: MutableMap<String, String> = mutableMapOf(ContentType to JsonMediaType, Accept to JsonMediaType)