Skip to content

Instantly share code, notes, and snippets.

@dave08
Created July 10, 2018 11:35
Show Gist options
  • Save dave08/b6df4b5d18ca9dff5530fa2d35a99f82 to your computer and use it in GitHub Desktop.
Save dave08/b6df4b5d18ca9dff5530fa2d35a99f82 to your computer and use it in GitHub Desktop.
@ContextDsl
fun Route.coGet(path: String, block: suspend ApplicationCall.() -> ServerResponse): Route = get("/") {
val result = call.block()
when (result) {
is ServerResponse.Empty ->
call.respondText { "" }
is ServerResponse.Json ->
call.respondText(result.jsonString, ContentType.Application.Json)
is ServerResponse.Error ->
call.respondText(ContentType.Application.Json, HttpStatusCode.fromValue(result.statusCode)) {
logger.error{ "${result.message}: caused by ${result.exception}" }
result.message
}
}
}
@soywiz
Copy link

soywiz commented Jul 10, 2018

Another possible alternative (I guess):

@ContextDsl fun Route.get(path: String): Route = get(path) { } // Note: Lambda intentionally empty
@ContextDsl fun Route.post(path: String): Route = post(path) { } // Note: Lambda intentionally empty

sealed class ServerResponse {
    object Empty : ServerResponse()

    data class Error(val statusCode: Int, val message: String, val exception: Exception? = null) : ServerResponse()

    data class Json(val jsonObj: Any) : ServerResponse() {
        val jsonString: String
            get() = Klaxon().toJsonString(jsonObj)
    }
}

fun Route.coHandler(block: suspend ApplicationCall.() -> ServerResponse): Route = this.apply {
    handle {
        val result = call.block()

        when (result) {
            is ServerResponse.Empty ->
                call.respondText { "" }

            is ServerResponse.Json ->
                call.respondText(result.jsonString, ContentType.Application.Json)

            is ServerResponse.Error ->
                call.respondText(ContentType.Application.Json, HttpStatusCode.fromValue(result.statusCode)) {
                    logger.error { "${result.message}: caused by ${result.exception}" }

                    result.message
                }
        }
    }
}

fun Application.mymodule() {
    routing {
        get("/").coHandler {
            ServerResponse.Empty
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment