Skip to content

Commit de08061

Browse files
authored
Merge pull request #191 from ikasovitch/encoding-workaround
Use an appropriate charset for json in case the request didn't specify a charset
2 parents 4187dc8 + 19ab94d commit de08061

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

kgraphql-ktor/src/main/kotlin/com/apurebase/kgraphql/KtorFeature.kt

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import io.ktor.request.*
99
import io.ktor.response.*
1010
import io.ktor.routing.*
1111
import io.ktor.util.*
12+
import java.nio.charset.Charset
1213
import kotlinx.coroutines.coroutineScope
1314
import kotlinx.serialization.json.*
1415
import kotlinx.serialization.json.Json.Default.decodeFromString
@@ -56,7 +57,8 @@ class GraphQL(val schema: Schema) {
5657
val routing: Route.() -> Unit = {
5758
route(config.endpoint) {
5859
post {
59-
val request = decodeFromString(GraphqlRequest.serializer(), call.receiveText())
60+
val bodyAsText = call.receiveTextWithCorrectEncoding()
61+
val request = decodeFromString(GraphqlRequest.serializer(), bodyAsText)
6062
val ctx = context {
6163
config.contextSetup?.invoke(this, call)
6264
}
@@ -90,6 +92,17 @@ class GraphQL(val schema: Schema) {
9092
return GraphQL(schema)
9193
}
9294

95+
private suspend fun ApplicationCall.receiveTextWithCorrectEncoding(): String {
96+
fun ContentType.defaultCharset(): Charset = when (this) {
97+
ContentType.Application.Json -> Charsets.UTF_8
98+
else -> Charsets.ISO_8859_1
99+
}
100+
101+
val contentType = request.contentType()
102+
val suitableCharset = contentType.charset() ?: contentType.defaultCharset()
103+
return receiveStream().bufferedReader(charset = suitableCharset).readText()
104+
}
105+
93106
private fun GraphQLError.serialize(): String = buildJsonObject {
94107
put("errors", buildJsonArray {
95108
addJsonObject {

0 commit comments

Comments
 (0)