Skip to content

Instantly share code, notes, and snippets.

@OlegIlyenko
Last active October 25, 2019 03:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save OlegIlyenko/660765354ac763efaed7970a487ae408 to your computer and use it in GitHub Desktop.
Save OlegIlyenko/660765354ac763efaed7970a487ae408 to your computer and use it in GitHub Desktop.
Simple example of a mutation with complex input type argument
import sangria.schema._
import sangria.execution._
import sangria.macros._
import sangria.macros.derive._
import sangria.marshalling.circe._
import scala.concurrent.ExecutionContext.Implicits.global
import io.circe.generic.auto._
// Some basic data structures
case class Author(name: String, publishedBooks: Int = 0)
case class Book(title: String, authors: Seq[Author])
// Stub repository to store the value
class Repo {
private var storedBook: Option[Book] = None
def saveBook(book: Book): Unit = {
storedBook = Some(book)
}
def loadBook(): Option[Book] = storedBook
}
// Input object defined explicitly
implicit val AuthorInputType = InputObjectType[Author]("AuthorInput", List(
InputField("name", StringType),
InputField("publishedBooks", IntType, defaultValue = 0)))
// Input object derived with macro
implicit val BookInputType = deriveInputObjectType[Book](
InputObjectTypeName("BookInput"))
// Output objects
implicit val AuthorType = deriveObjectType[Unit, Author]()
val BookType = deriveObjectType[Unit, Book]()
// Schema definition
val BookArg = Argument("book", BookInputType)
val QueryType = ObjectType("Query", fields[Repo, Unit](
Field("book", OptionType(BookType), resolve = _.ctx.loadBook())))
val MutationType = ObjectType("Mutation", fields[Repo, Unit](
Field("saveBook", OptionType(BookType),
arguments = BookArg :: Nil,
resolve = c ⇒ {
val book = c arg BookArg
c.ctx.saveBook(book)
book
})))
val schema = Schema(QueryType, Some(MutationType))
// Test query
val query =
gql"""
mutation {
saveBook(book: {title: "Sapiens", authors: [{name: "Yuval Noah Harari", publishedBooks: 6}]}) {
title
authors {
name
publishedBooks
}
}
}
"""
val context = new Repo
val result = Executor.execute(schema, query, context)
result.foreach(res ⇒ println(res.spaces2))
// Prints:
//
// {
// "data" : {
// "saveBook" : {
// "title" : "Sapiens",
// "authors" : [
// {
// "name" : "Yuval Noah Harari",
// "publishedBooks" : 6
// }
// ]
// }
// }
// }
@anotherhale
Copy link

anotherhale commented Sep 10, 2018

Thanks for the example. I just needed to add the JsonFormat to get it to work.

import play.api.libs.json._
import scala.concurrent.Future

  implicit val authorType = Json.format[Author]
  implicit val bookFormat = Json.format[Book]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment