Skip to content

Instantly share code, notes, and snippets.

View OlegIlyenko's full-sized avatar

ΘLΞG OlegIlyenko

View GitHub Profile
@OlegIlyenko
OlegIlyenko / ApolloCacheExtension.scala
Last active February 10, 2022 22:05
Example of Sangria middleware for Apollo Cache Control (https://github.com/apollographql/apollo-cache-control)
import sangria.ast._
import sangria.execution._
import sangria.schema.Context
import sangria.marshalling.queryAst._
import java.util.concurrent.ConcurrentLinkedQueue
import scala.concurrent.duration.FiniteDuration
import scala.collection.JavaConverters._
val UUIDType = ScalarAlias[UUID, String](StringType,
toScalar = _.toString,
fromScalar = idString ⇒ try Right(UUID.fromString(idString)) catch {
case _: IllegalArgumentException ⇒ Left(IDViolation)
})
case object IDViolation extends ValueCoercionViolation("Invalid ID")
@OlegIlyenko
OlegIlyenko / ApolloTracingExtension.scala
Last active May 15, 2018 20:35
An example of the apollo tracing GraphQL extension with Sangria
import java.time.Instant
import java.time.format.DateTimeFormatter
import java.util.concurrent.ConcurrentLinkedQueue
import sangria.ast._
import sangria.execution._
import sangria.schema.Context
import sangria.marshalling.queryAst._
import sangria.renderer.SchemaRenderer
class FieldMetrics(reporter: MetricsReporter)
extends Middleware[Any]
with MiddlewareAfterField[Any]
with MiddlewareErrorField[Any] {
type QueryVal = ()
type FieldVal = Long
def beforeQuery(context: MiddlewareQueryContext[Any, _, _]) = ()
def afterQuery(queryVal: QueryVal, context: MiddlewareQueryContext[Any, _, _]) = ()
{
"data": {
"human": {
"name": "Luke Skywalker",
"appearsIn": ["NEWHOPE", "EMPIRE", "JEDI"],
"friends": [
{"name": "Han Solo"},
{"name": "Leia Organa"},
{"name": "C-3PO"},
{"name": "R2-D2"}
# [Execution Metrics] duration: 1424ms, validation: 1ms, reducers: 0ms
{
# [Query] count: 1, time: 0ms
human(id: "1000") {
# [Human] count: 1, time: 0ms
name
# [Human] count: 1, time: 609ms
friends {
...Stuff
@OlegIlyenko
OlegIlyenko / sangria-slowlog-query.graphql
Last active June 18, 2017 18:02
Example of sangria-slowlog
# [Execution Metrics] duration: 12362ms, validation: 0ms, reducers: 0ms
#
# $id = "1000"
query Test($id: String!) {
# [Query] count: 1, time: 2ms
#
# $id = "1000"
human(id: $id) {
# [Human] count: 1, time: 0ms
name
object Args {
val empty = new Args(Map.empty, Set.empty, Set.empty, Set.empty, TrieMap.empty)
def apply(definitions: List[Argument[_]], values: (String, Any)*): Args =
apply(definitions, values.toMap)
def apply(definitions: List[Argument[_]], values: Map[String, Any]): Args =
apply(definitions, input = ScalaInput.scalaInput(values))
def apply[In: InputUnmarshaller](definitions: List[Argument[_]], input: In): Args = {
@OlegIlyenko
OlegIlyenko / 1.GivenThisGraphQLQuery.scala
Last active September 25, 2016 14:52
Sangria deferred resolution optimization - now deferred resolution is performed only once for every level of resolution (does not depend on a query nesting level)
case class LoadCategories(ids: Seq[String]) extends Deferred[Seq[String]]
lazy val CategoryType: ObjectType[Unit, String] = ObjectType("Category", () ⇒ fields[Unit, String](
Field("name", StringType, resolve = c ⇒ s"Cat ${c.value}"),
Field("children", ListType(CategoryType),
arguments = Argument("count", IntType) :: Nil,
resolve = c ⇒ LoadCategories((1 to c.arg[Int]("count")).map(i ⇒ s"${c.value}.$i")))
))
val QueryType = ObjectType("Query", fields[Unit, Unit](
@OlegIlyenko
OlegIlyenko / CustomJsonScalarType.scala
Last active March 4, 2022 16:48
An example of custom raw JSON scalar type in sangria. DON'T USE IT! By using it you lose many benefits of GraphQL. This just demonstrates that it is possible. If you tempted to expose it, then definitely think twice before using it.
import sangria.ast
import sangria.execution.Executor
import sangria.marshalling.{InputUnmarshaller, ScalarValueInfo, ArrayMapBuilder, ResultMarshaller}
import sangria.schema._
import sangria.validation.{ValueCoercionViolation, IntCoercionViolation, BigIntCoercionViolation}
import spray.json._
import sangria.macros._
import scala.concurrent.ExecutionContext.Implicits.global
implicit object CustomSprayJsonResultMarshaller extends ResultMarshaller {