From ac58b6a7e32cd2283ddfaa5254fd7c5939ac58ae Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Tue, 6 Sep 2022 21:16:41 +0600 Subject: [PATCH] bodyOrNull/respondOrNoContent --- CHANGELOG.md | 6 ++++++ .../inmo/micro_utils/ktor/client/BodyOrNull.kt | 9 +++++++++ .../micro_utils/ktor/server/RespondOrNoContent.kt | 15 +++++++++++++++ 3 files changed, 30 insertions(+) create mode 100644 ktor/client/src/commonMain/kotlin/dev/inmo/micro_utils/ktor/client/BodyOrNull.kt create mode 100644 ktor/server/src/jvmMain/kotlin/dev/inmo/micro_utils/ktor/server/RespondOrNoContent.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b8d726d8ea..3809c8f8fd4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## 0.12.8 +* `Ktor`: + * `Client`: + * New extension `HttpClient#bodyOrNull` which returns `null` in case when server responded with `No Content` (204) + * `Server`: + * New extension `ApplicationCall#respondOrNoContent` which responds `No Content` (204) when passed data is null + ## 0.12.7 * `Repos`: diff --git a/ktor/client/src/commonMain/kotlin/dev/inmo/micro_utils/ktor/client/BodyOrNull.kt b/ktor/client/src/commonMain/kotlin/dev/inmo/micro_utils/ktor/client/BodyOrNull.kt new file mode 100644 index 00000000000..55abf3b7c87 --- /dev/null +++ b/ktor/client/src/commonMain/kotlin/dev/inmo/micro_utils/ktor/client/BodyOrNull.kt @@ -0,0 +1,9 @@ +package dev.inmo.micro_utils.ktor.client + +import io.ktor.client.call.body +import io.ktor.client.statement.HttpResponse +import io.ktor.http.HttpStatusCode + +suspend inline fun HttpResponse.bodyOrNull() = takeIf { + status == HttpStatusCode.OK +} ?.body() diff --git a/ktor/server/src/jvmMain/kotlin/dev/inmo/micro_utils/ktor/server/RespondOrNoContent.kt b/ktor/server/src/jvmMain/kotlin/dev/inmo/micro_utils/ktor/server/RespondOrNoContent.kt new file mode 100644 index 00000000000..3bc770d1ede --- /dev/null +++ b/ktor/server/src/jvmMain/kotlin/dev/inmo/micro_utils/ktor/server/RespondOrNoContent.kt @@ -0,0 +1,15 @@ +package dev.inmo.micro_utils.ktor.server + +import io.ktor.http.HttpStatusCode +import io.ktor.server.application.ApplicationCall +import io.ktor.server.response.respond + +suspend inline fun ApplicationCall.respondOrNoContent( + data: T? +) { + if (data == null) { + respond(HttpStatusCode.NoContent) + } else { + respond(data) + } +}