Skip to content

Instantly share code, notes, and snippets.

@shishkin
Created December 1, 2016 03:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shishkin/8771d6310f3784dac0e325cd89cbc250 to your computer and use it in GitHub Desktop.
Save shishkin/8771d6310f3784dac0e325cd89cbc250 to your computer and use it in GitHub Desktop.
Sangria scalar type derived from Circe encoder and decoder
package org.shishkin.sangria
import cats.syntax.either._
import io.circe._
import sangria.execution.Resolver
import sangria.marshalling.circe._
import sangria.schema._
import sangria.validation.Violation
import scala.language.implicitConversions
import scala.reflect._
import scala.util._
package object schema {
implicit def decodeResultAsEither[A](r: Decoder.Result[A]): Either[Violation, A] =
r.leftMap(failure => CoercionViolation(failure.getMessage()))
def deriveScalarType[A: ClassTag](implicit decoder: Decoder[A], encoder: Encoder[A]): ScalarType[A] = {
val name = classTag[A].runtimeClass.getSimpleName
ScalarType(
name = name,
coerceOutput = (v, _) =>
CirceInputUnmarshaller.getScalarValue(encoder(v)),
coerceUserInput = v =>
decoder.decodeJson(CirceResultMarshaller.scalarNode(v, name, Set())),
coerceInput = v =>
decoder.decodeJson(Resolver.marshalScalarValue(v, CirceResultMarshaller, name, Set())))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment