sangria-graphql / sangria-circe

Sangria circe marshalling
Apache License 2.0
24 stars 19 forks source link

equivalent to sangria.marshalling.sprayJson.sprayJsonReaderFromInput? #13

Closed evbo closed 6 years ago

evbo commented 6 years ago

Hi,

What is the equivalent import for circe for the following sprayJson?: import sangria.marshalling.sprayJson.sprayJsonReaderFromInput

In migrating from sprayJson to circe, I've tried using import sangria.marshalling.circe.circeFromInput

But I still get error:

Error:(58, 146) Type Option[Seq[Metric @@ sangria.marshalling.FromInput.InputObjectResult]] cannot be used as an input. Please consider defining an implicit instance of `FromInput` for it.

Here is how my spray implementation worked:

trait InputJsonFormat extends DefaultJsonProtocol {
  implicit val metricFilterFormat = jsonFormat4(Metric)
}

object Resolvers extends InputJsonFormat {

val MetricType = deriveInputObjectType[Metric]()

  val queryType = ObjectType(
    "Query", "Required root object that contains all types",
    fields[Context, Unit](

      Field("getMetrics", ListType(MetricsType),
        arguments = List(Argument("metric", OptionInputType(ListInputType(MetricType)))),
        resolve = c => c.ctx.dao.getMetrics(c.argOpt[Seq[Metric]]("metric"))
      ),
  )
}
OlegIlyenko commented 6 years ago

Circe type-class based JSON deserialization is quite similar to spray-json. Circe uses Encoder and Decoder type-classes for this. Sungria supports these via:

sangria.marshalling.circe.{circeEncoderToInput, circeDecoderFromInput}

Circe provides various mechanisms to define the decoders, for example you can write them manually or you can derive them from the case classes (similar to what spray-json provides). Here is an example of how you can take advantage of fully automatic derivation:

import io.circe.generic.auto._
import io.circe.syntax._
import sangria.marshalling.circe._

val MetricType = deriveInputObjectType[Metric]()
val MetricArg = Argument("metric", OptionInputType(ListInputType(MetricType)))

val QueryType = ObjectType("Query", "Required root object that contains all types",
  fields[Context, Unit](
    Field("getMetrics", ListType(MetricsType),
      arguments = MetricArg :: Nil,
      resolve = c ⇒ c.ctx.dao.getMetrics(c arg MetricArg))))
evbo commented 6 years ago

Thank you and sorry for the late response. So it appears that with circe I needed the following import that was missing:

import sangria.marshalling.circe._

That's all the magic it took! Now it's compiling, thank you!

cristinarc commented 6 years ago

It took me also quite some time to find out that this line was what was missing. Thanks for sharing it!