Skip to content

Commit

Permalink
Merge pull request #191 from ikasovitch/encoding-workaround
Browse files Browse the repository at this point in the history
Use an appropriate charset for json in case the request didn't specify a charset
  • Loading branch information
jeggy authored Jul 2, 2022
2 parents 4187dc8 + 19ab94d commit de08061
Showing 1 changed file with 14 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import io.ktor.request.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.util.*
import java.nio.charset.Charset
import kotlinx.coroutines.coroutineScope
import kotlinx.serialization.json.*
import kotlinx.serialization.json.Json.Default.decodeFromString
Expand Down Expand Up @@ -56,7 +57,8 @@ class GraphQL(val schema: Schema) {
val routing: Route.() -> Unit = {
route(config.endpoint) {
post {
val request = decodeFromString(GraphqlRequest.serializer(), call.receiveText())
val bodyAsText = call.receiveTextWithCorrectEncoding()
val request = decodeFromString(GraphqlRequest.serializer(), bodyAsText)
val ctx = context {
config.contextSetup?.invoke(this, call)
}
Expand Down Expand Up @@ -90,6 +92,17 @@ class GraphQL(val schema: Schema) {
return GraphQL(schema)
}

private suspend fun ApplicationCall.receiveTextWithCorrectEncoding(): String {
fun ContentType.defaultCharset(): Charset = when (this) {
ContentType.Application.Json -> Charsets.UTF_8
else -> Charsets.ISO_8859_1
}

val contentType = request.contentType()
val suitableCharset = contentType.charset() ?: contentType.defaultCharset()
return receiveStream().bufferedReader(charset = suitableCharset).readText()
}

private fun GraphQLError.serialize(): String = buildJsonObject {
put("errors", buildJsonArray {
addJsonObject {
Expand Down

0 comments on commit de08061

Please sign in to comment.