Skip to content
This repository was archived by the owner on Feb 2, 2024. It is now read-only.

boonoboo/Kodegen

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

63 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Kodegen

Kodegen is a library for automatic generation of web API endpoints and API client methods for Ktor applications.

Usage

In your build.gradle, add Kodegen to your dependencies:

dependencies {
    implementation("dk.cachet:kodegen:1.0.0")
}

To generate code, add the dependencies using the kapt configuration:

dependencies {
    kapt("dk.cachet:kodegen:1.0.0")
}

Examples

Basic use

Given the following application service:

@ApplicationService
class ExampleService() {
    suspend fun foo(bar: Baz): Qux
}

Kodegen will, on compilation, generate the following Ktor module:

fun Application.ExampleServiceModule(service: ExampleService, vararg authSchemes: String) {
  routing {
    post("/kodegenApi/exampleService/foo/") {
      val request = call.receive<FooRequest>()
      val bar = request.bar
      val result = service.foo(bar)
      call.respond(result = result)
    }
  }
}

and the following client class:

class ExampleServiceInvoker(val client: HttpClient, val json: Json, val baseUrl: String) {
    suspend fun foo(bar: Baz): Qux {
    val jsonBody = json.stringify(FooRequest.serializer(), FooRequest(bar = bar))
    val response = client.post<String> {
        url("$baseUrl/kodegenApi/dateService/foo")
        body = TextContent(jsonBody, ContentType.Application.Json)
    }
    val result = json.parse(FooResponse.serializer(), response).result
    return result
}

using the following request and response objects:

@Serializable
data class ExampleServiceFooRequest(val bar: Baz)
@Serializable
data class ExampleServiceFooResponse(val result: Qux)

Authentication

The RequiresAuthentication annotation is used to indicate that a user should be authenticated before a method is called. Using it will add an authentication interceptor before routing to the endpoint. The authentication schemes to use for this are passed as parameters to the Ktor module.

Thus, adding RequiresAuthentication to the method foo:

@RequiresAuthentication
fun foo(bar: Baz): Qux
{
    ...
}

results in the route:

authenticate(*authSchemes) {
    post("/kodegenApi/exampleService/foo/") {
        ...
    }
}

About

Kotlin library for automatic generation of Ktor Application modules and Ktor HttpClient methods.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages