sangria-graphql / sangria

Scala GraphQL implementation
https://sangria-graphql.github.io
Apache License 2.0
1.96k stars 226 forks source link

Is the query result accessible in the `Middleware Extensions`? #372

Closed daewon closed 6 years ago

daewon commented 6 years ago

I was wondering when I was looking at the Middleware Extensions entry and creating an extension.

In the described middleware, the value of context.queryAst is stringifed json and included in the result.

I want to change the result value to another format (eg: xml string) instead of input query

For the below results, the result objects should be accessible in the middleware.

But i could not find a way. How can i access result object in the afterQueryExtensions method.

{
   "data": {
      "human": {
         "name": "Luke Skywalker"
      }
   },
   "extensions": {
      "xml": "<human><name>Luke Skywalker</name></human>"
   }
}
daewon commented 6 years ago

I solved the problem by mix-in the MiddlewareAfterField trait with the code below.

object SigmaJSFormatted extends Middleware [Any] with MiddlewareAfterField [Any] with MiddlewareExtension [Any] {}

I collected the value in the afterField method and painted the result in the value in afterQueryExtensions method.

I wonder if this usage is proper usage.

Thank you for creating a good framework.

OlegIlyenko commented 6 years ago

MiddlewareExtension is definitely can be useful in some scenarios, but I think in this case you don't really need it (also, it will not give you the execution result). Something simple like this should do the trick:

import io.circe._
import sangria.marshalling.circe._

Executor.execute(schema, query).map(resultJson ⇒
  Json.fromJsonObject(
    resultJson.asObject.get
      .add("extensions", Json.obj("xml" → Json.fromString(jsonToXml(resultJson))))))

After the execution is done, you can just add XML version as an extension in the JSON directly.