Last active
October 25, 2019 03:58
-
-
Save OlegIlyenko/660765354ac763efaed7970a487ae408 to your computer and use it in GitHub Desktop.
Simple example of a mutation with complex input type argument
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
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 | |
// } | |
// ] | |
// } | |
// } | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the example. I just needed to add the JsonFormat to get it to work.