我有一个应该处理GraphQL POST查询的PlayServiceCall。代码如下 -
override def restPostCall: PlayServiceCall[String, String] = PlayServiceCall { request =>
Action.async(parse.json) { request =>
val query = (request.body \ "query").as[String]
val operation = (request.body \ "operationName").asOpt[String]
val variables = (request.body \ "variables").toOption.map {
case obj: JsObject => obj
case _ => Json.obj()
}
QueryParser.parse(query) match {
// query parsed successfully, time to execute it!
case Success(queryAst) ⇒
executeGraphQLQuery(queryAst, operation, variables getOrElse Json.obj())
// can't parse GraphQL query, return error
case Failure(error: SyntaxError) ⇒
Future.successful(BadRequest(Json.obj("error" → error.getMessage)))
}
}
}
代码与Sangria网站上的“入门”页面中解释的代码相同,代码也是example project on Github by Sangria的代码。这里graphqlBody方法处理GraphQL的POST请求。
当我通过 POST 方法发送GraphQL查询时,它会出现以下错误 -
For request 'POST /graphql' [Invalid Json: Unrecognized token 'query': was expecting ('true', 'false' or 'null') at [Source: akka.util.ByteIterator$ByteArrayIterator$$anon$1@10f6774; line: 1, column: 7]]
任何人都可以帮助如何通过POST方法使用Sangria发送GraphQL查询。
答案 0 :(得分:1)
嘿伙计们我刚刚找到了解决方案。仍然需要以JSON格式发送查询,如此
{
"query" : "query HeroAndFriends { hero {name friends { name }}}"
}