Created
October 13, 2016 23:03
-
-
Save trbngr/571e7fc2b98c4c5559ab9af2e4dc802d to your computer and use it in GitHub Desktop.
Parse GraphQl Request with Circe.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
case class GraphQlRequest(query: String, operation: Option[String], variables: Json) | |
def parseRequest: Directive1[GraphQlRequest] = { | |
import cats.data.Xor | |
import io.circe.ParsingFailure | |
import io.circe.parser.{parse ⇒ parseJson} | |
entity(as[Json]).map { json ⇒ | |
val cursor = json.hcursor | |
val variables = { | |
val field = cursor.downField("variables") | |
field.as[String] match { | |
case Xor.Right(jsonString) ⇒ parseJson(jsonString) | |
case _ ⇒ field.as[Json] match { | |
case jsonObject: Xor.Right[Json] ⇒ jsonObject | |
case Xor.Left(failure) ⇒ Xor.Left(ParsingFailure(failure.getMessage(), failure)) | |
} | |
} | |
} | |
GraphQlRequest( | |
query = cursor.downField("query").as[String].getOrElse(throw new RuntimeException("Missing query")), | |
operation = cursor.downField("operationName").as[Option[String]].getOrElse(Option.empty[String]), | |
variables = variables getOrElse Json.obj() | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A version that uses circe's semi automatic derivation.
and then use
entity(as[GraphQLQuery])
and passGraphQLQuery.variables.getOrElse(Json.obj())
to Sangria.