deferOpt
— Code, Scala, Sangria, Backend — 1 min read
The problem
I might have an Id of something Option[x]
, if it's there, fetch it!, otherwise don't
The solution
Use DeferOpt
Here's an example
import sangria.execution.deferred.Deferredimport sangria.macros.derive._import sangria.schema._
// Assume you have a simple data modelcase class Book(id: Int, title: String)
object BookData { private val books = List( Book(1, "Book 1"), Book(2, "Book 2"), Book(3, "Book 3") )
def getBookById(id: Int): Option[Book] = books.find(_.id == id)}
// Define a GraphQL schemaval BookType = deriveObjectType[Unit, Book]()
val QueryType = ObjectType( "Query", fields[Unit, Unit]( Field("book", OptionType(BookType), arguments = List(Argument("id", IntType)), resolve = ctx => DeferredValue(BookData.getBookById(ctx.args.arg[Int]("id"))) ) ))
val schema = Schema(QueryType)
// Now you can use `deferOpt` in your queryval query = graphql""" query { book(id: 1) @deferOpt { title } } """
// Resolve the queryimport sangria.execution.{Executor, QueryAnalysisError}
val result = Executor.execute(schema, query, deferredResolver = sangria.execution.deferred.DeferOptResolver.fetchDeferred)
// Print the resultimport scala.concurrent.Awaitimport scala.concurrent.duration._
val eventualResult = result.map(_.toString)val resultString = Await.result(eventualResult, 5.seconds)println(resultString)