Skip to content

Commit

Permalink
fix: UTF-8 handling for request bodies (#1120)
Browse files Browse the repository at this point in the history
* fix: UTF-8 handling for request bodies

zio-http just does body.bytes.map(_.toChar) which breaks
for UTF-8 encoded bodies.

* properly sniff charset
  • Loading branch information
frekw authored Nov 1, 2021
1 parent 338123c commit 62f2264
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions adapters/zio-http/src/main/scala/caliban/ZHttpAdapter.scala
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@ import caliban.execution.QueryExecution
import io.circe._
import io.circe.parser._
import io.circe.syntax._
import io.netty.handler.codec.http.HttpHeaderNames
import io.netty.handler.codec.http.HttpUtil
import java.nio.charset.Charset
import zhttp.http._
import zhttp.socket.SocketApp
import zhttp.socket.WebSocketFrame.Text
import zhttp.socket._
import io.netty.handler.codec.http.HttpHeaderNames

object ZHttpAdapter {
case class GraphQLWSRequest(`type`: String, id: Option[String], payload: Option[Json])
Expand Down Expand Up @@ -243,10 +245,22 @@ object ZHttpAdapter {
if (req.url.queryParams.contains("query")) {
queryFromQueryParams(req)
} else if (req.headers.contains(contentTypeApplicationGraphQL)) {
ZIO.succeed(GraphQLRequest(query = req.getBodyAsString))
ZIO.succeed(GraphQLRequest(query = getBody(req)))
} else {
ZIO.fromEither(decode[GraphQLRequest](req.getBodyAsString.getOrElse("")))
ZIO.fromEither(decode[GraphQLRequest](getBody(req).getOrElse("")))
}

// Fixed in https://github.com/dream11/zio-http/pull/287
// but that's not released, so back port the fix for now.
private def getBody(r: Request): Option[String] = {
val getCharset: Option[Charset] =
r.getHeaderValue(HttpHeaderNames.CONTENT_TYPE).map(HttpUtil.getCharset(_, HTTP_CHARSET))

r.content match {
case HttpData.CompleteData(data) => Some(new String(data.toArray, getCharset.getOrElse(HTTP_CHARSET)))
case _ => None
}
}

private def generateGraphQLResponse[R, E](
payload: GraphQLRequest,
Expand Down

0 comments on commit 62f2264

Please sign in to comment.