Created
December 1, 2016 03:03
-
-
Save shishkin/8771d6310f3784dac0e325cd89cbc250 to your computer and use it in GitHub Desktop.
Sangria scalar type derived from Circe encoder and decoder
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
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