Skip to content

Instantly share code, notes, and snippets.

@nickhudkins
Created October 6, 2021 00:23
Show Gist options
  • Save nickhudkins/a001668419325e88e99106389dacefae to your computer and use it in GitHub Desktop.
Save nickhudkins/a001668419325e88e99106389dacefae to your computer and use it in GitHub Desktop.
Sangria Snippets
// When using an Input field in which you would like to enforce validation at query validation time
// via.... types, you will need a custom JSON marshaller, as well as a `ScalarType` to allow for...
// custom scalar types to be used as an Input. This does not come up as often for custom output types
// as `.toString` allows for most complex types to be easily serialized as a `String`
object LocaleSupport {
import io.circe.Decoder
private val VIOLATION_MESSAGE = "Invalid Locale Provided"
// Custom Java Exception
final case class InvalidLocaleException(
private val message: String = VIOLATION_MESSAGE,
private val cause: Throwable = None.orNull
) extends Exception(message, cause)
// Sangria Violation
case object LocaleViolation extends ValueCoercionViolation(VIOLATION_MESSAGE)
// Implement however
def parseLocale(s: String): Either[LocaleViolation.type, Locale] = ???
// JSON decoding
implicit val decodeLocale: Decoder[Locale] = Decoder.decodeString.emapTry{ s => {
val res = parseLocale(s)
res match {
case Right(l) => Success(l)
case Left(_) => Failure(new InvalidLocaleException)
}
}}
implicit val LocaleType: ScalarType[Locale] = ScalarType[Locale]("Locale",
coerceOutput = (d, _) => d.toString,
coerceUserInput = {
case s: String => parseLocale(s)
case _ => Left(LocaleViolation)
},
coerceInput = {
case sangria.ast.StringValue(s, _, _, _, _) => parseLocale(s)
case _ => Left(LocaleViolation)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment