├── project ├── build.properties └── plugins.sbt ├── app.json ├── .gitignore ├── src ├── main │ └── scala │ │ ├── CorsSupport.scala │ │ ├── Server.scala │ │ ├── Data.scala │ │ └── SchemaDefinition.scala └── test │ └── scala │ └── SchemaSpec.scala ├── .github └── workflows │ ├── ci.yml │ └── clean.yml ├── README.md └── LICENSE /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.11.7 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("io.spray" % "sbt-revolver" % "0.10.0") 2 | addSbtPlugin("com.heroku" % "sbt-heroku" % "2.1.4") 3 | addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.11.4") 4 | addSbtPlugin("com.github.sbt" % "sbt-github-actions" % "0.28.0") 5 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Sangria akka-http Example", 3 | "description": "An example GraphQL server written with akka-http and sangria.", 4 | "repository": "https://github.com/sangria-graphql/sangria-akka-http-example", 5 | "logo": "https://raw.githubusercontent.com/sangria-graphql/sangria-logo/master/sangria-icon.png", 6 | "keywords": ["scala", "sangria", "graphql"] 7 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.log 3 | 4 | # VSCode 5 | .vscode 6 | 7 | # idea 8 | .idea 9 | .idea_modules 10 | 11 | # sbt specific 12 | dist/* 13 | target/ 14 | lib_managed/ 15 | src_managed/ 16 | project/boot/ 17 | project/project/ 18 | project/metals.sbt 19 | project/plugins/project/ 20 | 21 | .metals/ 22 | .bloop/ 23 | .bsp/ 24 | metals.sbt 25 | 26 | # Scala-IDE specific 27 | .scala_dependencies 28 | .bloop 29 | .metals 30 | .vscode/ 31 | -------------------------------------------------------------------------------- /src/main/scala/CorsSupport.scala: -------------------------------------------------------------------------------- 1 | import akka.http.scaladsl.model.HttpMethods._ 2 | import akka.http.scaladsl.model.headers._ 3 | import akka.http.scaladsl.model.{HttpResponse, StatusCodes} 4 | import akka.http.scaladsl.server.Directives._ 5 | import akka.http.scaladsl.server.{Directive0, Route} 6 | 7 | trait CorsSupport { 8 | private def addAccessControlHeaders: Directive0 = 9 | respondWithHeaders( 10 | `Access-Control-Allow-Origin`.*, 11 | `Access-Control-Allow-Credentials`(true), 12 | `Access-Control-Allow-Headers`("Authorization", "Content-Type", "X-Requested-With") 13 | ) 14 | 15 | private def preflightRequestHandler: Route = options { 16 | complete(HttpResponse(StatusCodes.OK) 17 | .withHeaders( 18 | `Access-Control-Allow-Methods`(OPTIONS, POST, GET) 19 | ) 20 | ) 21 | } 22 | 23 | def corsHandler(r: Route): Route = addAccessControlHeaders { 24 | preflightRequestHandler ~ r 25 | } 26 | } -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | # This file was automatically generated by sbt-github-actions using the 2 | # githubWorkflowGenerate task. You should add and commit this file to 3 | # your git repository. It goes without saying that you shouldn't edit 4 | # this file by hand! Instead, if you wish to make changes, you should 5 | # change your sbt build configuration to revise the workflow description 6 | # to meet your needs, then regenerate this file. 7 | 8 | name: Continuous Integration 9 | 10 | on: 11 | pull_request: 12 | branches: ['**'] 13 | push: 14 | branches: ['**'] 15 | 16 | env: 17 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 18 | 19 | jobs: 20 | build: 21 | name: Build and Test 22 | strategy: 23 | matrix: 24 | os: [ubuntu-latest] 25 | scala: [2.13.17] 26 | java: [zulu@8] 27 | runs-on: ${{ matrix.os }} 28 | steps: 29 | - name: Checkout current branch (full) 30 | uses: actions/checkout@v5 31 | with: 32 | fetch-depth: 0 33 | 34 | - name: Setup Java (zulu@8) 35 | if: matrix.java == 'zulu@8' 36 | uses: actions/setup-java@v5 37 | with: 38 | distribution: zulu 39 | java-version: 8 40 | cache: sbt 41 | 42 | - name: Setup sbt 43 | uses: sbt/setup-sbt@v1 44 | 45 | - name: Check that workflows are up to date 46 | run: sbt '++ ${{ matrix.scala }}' githubWorkflowCheck 47 | 48 | - name: Build project 49 | run: sbt '++ ${{ matrix.scala }}' test 50 | -------------------------------------------------------------------------------- /src/main/scala/Server.scala: -------------------------------------------------------------------------------- 1 | import scala.util.{Failure, Success} 2 | import sangria.execution.deferred.DeferredResolver 3 | import sangria.execution.{ErrorWithResolver, Executor, QueryAnalysisError} 4 | import sangria.slowlog.SlowLog 5 | import akka.actor.ActorSystem 6 | import akka.http.scaladsl.Http 7 | import akka.http.scaladsl.model.StatusCodes._ 8 | import akka.http.scaladsl.server.Directives._ 9 | import akka.http.scaladsl.server._ 10 | import sangria.marshalling.circe._ 11 | 12 | // This is the trait that makes `graphQLPlayground and prepareGraphQLRequest` available 13 | import sangria.http.akka.circe.CirceHttpSupport 14 | 15 | object Server extends App with CorsSupport with CirceHttpSupport { 16 | implicit val system: ActorSystem = ActorSystem("sangria-server") 17 | import system.dispatcher 18 | 19 | val route: Route = 20 | optionalHeaderValueByName("X-Apollo-Tracing") { tracing => 21 | path("graphql") { 22 | graphQLPlayground ~ 23 | prepareGraphQLRequest { 24 | case Success(req) => 25 | val middleware = if (tracing.isDefined) SlowLog.apolloTracing :: Nil else Nil 26 | val deferredResolver = DeferredResolver.fetchers(SchemaDefinition.characters) 27 | val graphQLResponse = Executor.execute( 28 | schema = SchemaDefinition.StarWarsSchema, 29 | queryAst = req.query, 30 | userContext = new CharacterRepo, 31 | variables = req.variables, 32 | operationName = req.operationName, 33 | middleware = middleware, 34 | deferredResolver = deferredResolver 35 | ).map(OK -> _) 36 | .recover { 37 | case error: QueryAnalysisError => BadRequest -> error.resolveError 38 | case error: ErrorWithResolver => InternalServerError -> error.resolveError 39 | } 40 | complete(graphQLResponse) 41 | case Failure(preparationError) => complete(BadRequest, formatError(preparationError)) 42 | } 43 | } 44 | } ~ 45 | (get & pathEndOrSingleSlash) { 46 | redirect("/graphql", PermanentRedirect) 47 | } 48 | 49 | val PORT = sys.props.get("http.port").fold(8080)(_.toInt) 50 | val INTERFACE = "0.0.0.0" 51 | Http().newServerAt(INTERFACE, PORT).bindFlow(corsHandler(route)) 52 | } 53 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Sangria akka-http Example 2 | 3 | An example [GraphQL](https://graphql.org) server written with [akka-http](https://github.com/akka/akka-http), [circe](https://github.com/circe/circe) and [sangria](https://github.com/sangria-graphql/sangria). 4 | 5 | [![Deploy](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy) 6 | 7 | After starting the server with 8 | 9 | ```bash 10 | sbt run 11 | 12 | # or, if you want to watch the source code changes 13 | 14 | sbt ~reStart 15 | ``` 16 | 17 | you can run queries interactively using [graphql-playground](https://github.com/prisma/graphql-playground) by opening [http://localhost:8080](http://localhost:8080) in a browser or query the `/graphql` endpoint directly. The HTTP endpoint follows [GraphQL best practices for handling the HTTP requests](http://graphql.org/learn/serving-over-http/#http-methods-headers-and-body). 18 | 19 | Here are some examples of the queries you can make: 20 | 21 | ```bash 22 | $ curl -X POST localhost:8080/graphql \ 23 | -H "Content-Type:application/json" \ 24 | -d '{"query": "{hero {name, friends {name}}}"}' 25 | ``` 26 | 27 | this gives back the hero of StarWars Saga together with the list of his friends, which is of course R2-D2: 28 | 29 | ```json 30 | { 31 | "data": { 32 | "hero": { 33 | "name": "R2-D2", 34 | "friends": [ 35 | { 36 | "name": "Luke Skywalker" 37 | }, 38 | { 39 | "name": "Han Solo" 40 | }, 41 | { 42 | "name": "Leia Organa" 43 | } 44 | ] 45 | } 46 | } 47 | } 48 | ``` 49 | 50 | Here is another example, which uses variables: 51 | 52 | ```bash 53 | $ curl -X POST localhost:8080/graphql \ 54 | -H "Content-Type:application/json" \ 55 | -d '{"query": "query Test($humanId: String!){human(id: $humanId) {name, homePlanet, friends {name}}}", "variables": {"humanId": "1000"}}' 56 | ``` 57 | 58 | The result should be something like this: 59 | 60 | ```json 61 | { 62 | "data": { 63 | "human": { 64 | "name": "Luke Skywalker", 65 | "homePlanet": "Tatooine", 66 | "friends": [ 67 | { 68 | "name": "Han Solo" 69 | }, 70 | { 71 | "name": "Leia Organa" 72 | }, 73 | { 74 | "name": "C-3PO" 75 | }, 76 | { 77 | "name": "R2-D2" 78 | } 79 | ] 80 | } 81 | } 82 | } 83 | ``` 84 | -------------------------------------------------------------------------------- /.github/workflows/clean.yml: -------------------------------------------------------------------------------- 1 | # This file was automatically generated by sbt-github-actions using the 2 | # githubWorkflowGenerate task. You should add and commit this file to 3 | # your git repository. It goes without saying that you shouldn't edit 4 | # this file by hand! Instead, if you wish to make changes, you should 5 | # change your sbt build configuration to revise the workflow description 6 | # to meet your needs, then regenerate this file. 7 | 8 | name: Clean 9 | 10 | on: push 11 | 12 | permissions: 13 | actions: write 14 | 15 | jobs: 16 | delete-artifacts: 17 | name: Delete Artifacts 18 | runs-on: ubuntu-latest 19 | env: 20 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 21 | steps: 22 | - name: Delete artifacts 23 | shell: bash {0} 24 | run: | 25 | # Customize those three lines with your repository and credentials: 26 | REPO=${GITHUB_API_URL}/repos/${{ github.repository }} 27 | 28 | # A shortcut to call GitHub API. 29 | ghapi() { curl --silent --location --user _:$GITHUB_TOKEN "$@"; } 30 | 31 | # A temporary file which receives HTTP response headers. 32 | TMPFILE=$(mktemp) 33 | 34 | # An associative array, key: artifact name, value: number of artifacts of that name. 35 | declare -A ARTCOUNT 36 | 37 | # Process all artifacts on this repository, loop on returned "pages". 38 | URL=$REPO/actions/artifacts 39 | while [[ -n "$URL" ]]; do 40 | 41 | # Get current page, get response headers in a temporary file. 42 | JSON=$(ghapi --dump-header $TMPFILE "$URL") 43 | 44 | # Get URL of next page. Will be empty if we are at the last page. 45 | URL=$(grep '^Link:' "$TMPFILE" | tr ',' '\n' | grep 'rel="next"' | head -1 | sed -e 's/.*.*//') 46 | rm -f $TMPFILE 47 | 48 | # Number of artifacts on this page: 49 | COUNT=$(( $(jq <<<$JSON -r '.artifacts | length') )) 50 | 51 | # Loop on all artifacts on this page. 52 | for ((i=0; $i < $COUNT; i++)); do 53 | 54 | # Get name of artifact and count instances of this name. 55 | name=$(jq <<<$JSON -r ".artifacts[$i].name?") 56 | ARTCOUNT[$name]=$(( $(( ${ARTCOUNT[$name]} )) + 1)) 57 | 58 | id=$(jq <<<$JSON -r ".artifacts[$i].id?") 59 | size=$(( $(jq <<<$JSON -r ".artifacts[$i].size_in_bytes?") )) 60 | printf "Deleting '%s' #%d, %'d bytes\n" $name ${ARTCOUNT[$name]} $size 61 | ghapi -X DELETE $REPO/actions/artifacts/$id 62 | done 63 | done 64 | -------------------------------------------------------------------------------- /src/test/scala/SchemaSpec.scala: -------------------------------------------------------------------------------- 1 | import sangria.ast.Document 2 | import sangria.macros._ 3 | import sangria.execution.Executor 4 | import sangria.execution.deferred.DeferredResolver 5 | import sangria.marshalling.circe._ 6 | import io.circe._ 7 | import io.circe.parser._ 8 | 9 | import scala.concurrent.Await 10 | import scala.concurrent.duration._ 11 | import scala.concurrent.ExecutionContext.Implicits.global 12 | import SchemaDefinition.StarWarsSchema 13 | import org.scalatest.matchers.should.Matchers 14 | import org.scalatest.wordspec.AnyWordSpec 15 | import sangria.marshalling.circe.CirceResultMarshaller.Node 16 | 17 | class SchemaSpec extends AnyWordSpec with Matchers { 18 | "StartWars Schema" should { 19 | "correctly identify R2-D2 as the hero of the Star Wars Saga" in { 20 | val query = 21 | graphql""" 22 | query HeroNameQuery { 23 | hero { 24 | name 25 | } 26 | } 27 | """ 28 | 29 | executeQuery(query) should be (parse( 30 | """ 31 | { 32 | "data": { 33 | "hero": { 34 | "name": "R2-D2" 35 | } 36 | } 37 | } 38 | """).getOrElse(fail("Failed to parse expected JSON. Please confirm the JSON is valid."))) 39 | } 40 | 41 | "allow to fetch Han Solo using his ID provided through variables" in { 42 | val query = 43 | graphql""" 44 | query FetchSomeIDQuery($$humanId: String!) { 45 | human(id: $$humanId) { 46 | name 47 | friends { 48 | id 49 | name 50 | } 51 | } 52 | } 53 | """ 54 | 55 | executeQuery(query, vars = Json.obj("humanId" -> Json.fromString("1002"))) should be (parse( 56 | """ 57 | { 58 | "data": { 59 | "human": { 60 | "name": "Han Solo", 61 | "friends": [ 62 | { 63 | "id": "1000", 64 | "name": "Luke Skywalker" 65 | }, 66 | { 67 | "id": "1003", 68 | "name": "Leia Organa" 69 | }, 70 | { 71 | "id": "2001", 72 | "name": "R2-D2" 73 | } 74 | ] 75 | } 76 | } 77 | } 78 | """).getOrElse(fail("Failed to parse expected JSON. Please confirm the JSON is valid."))) 79 | } 80 | } 81 | 82 | def executeQuery(query: Document, vars: Json = Json.obj()): Node = { 83 | val futureResult = Executor.execute(StarWarsSchema, query, 84 | variables = vars, 85 | userContext = new CharacterRepo, 86 | deferredResolver = DeferredResolver.fetchers(SchemaDefinition.characters)) 87 | 88 | Await.result(futureResult, 10.seconds) 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/scala/Data.scala: -------------------------------------------------------------------------------- 1 | object Episode extends Enumeration { 2 | val NEWHOPE, EMPIRE, JEDI = Value 3 | } 4 | 5 | trait Character { 6 | def id: String 7 | def name: Option[String] 8 | def friends: List[String] 9 | def appearsIn: List[Episode.Value] 10 | } 11 | 12 | case class Human( 13 | id: String, 14 | name: Option[String], 15 | friends: List[String], 16 | appearsIn: List[Episode.Value], 17 | homePlanet: Option[String]) extends Character 18 | 19 | case class Droid( 20 | id: String, 21 | name: Option[String], 22 | friends: List[String], 23 | appearsIn: List[Episode.Value], 24 | primaryFunction: Option[String]) extends Character 25 | 26 | class CharacterRepo { 27 | import CharacterRepo._ 28 | 29 | def getHero(episode: Option[Episode.Value]): Character = 30 | episode flatMap (_ => getHuman("1000")) getOrElse droids.last 31 | 32 | def getHuman(id: String): Option[Human] = humans.find(c => c.id == id) 33 | 34 | def getDroid(id: String): Option[Droid] = droids.find(c => c.id == id) 35 | 36 | def getHumans(limit: Int, offset: Int): List[Human] = humans.slice(offset, offset + limit) 37 | 38 | def getDroids(limit: Int, offset: Int): List[Droid] = droids.slice(offset, offset + limit) 39 | } 40 | 41 | object CharacterRepo { 42 | val humans = List( 43 | Human( 44 | id = "1000", 45 | name = Some("Luke Skywalker"), 46 | friends = List("1002", "1003", "2000", "2001"), 47 | appearsIn = List(Episode.NEWHOPE, Episode.EMPIRE, Episode.JEDI), 48 | homePlanet = Some("Tatooine")), 49 | Human( 50 | id = "1001", 51 | name = Some("Darth Vader"), 52 | friends = List("1004"), 53 | appearsIn = List(Episode.NEWHOPE, Episode.EMPIRE, Episode.JEDI), 54 | homePlanet = Some("Tatooine")), 55 | Human( 56 | id = "1002", 57 | name = Some("Han Solo"), 58 | friends = List("1000", "1003", "2001"), 59 | appearsIn = List(Episode.NEWHOPE, Episode.EMPIRE, Episode.JEDI), 60 | homePlanet = None), 61 | Human( 62 | id = "1003", 63 | name = Some("Leia Organa"), 64 | friends = List("1000", "1002", "2000", "2001"), 65 | appearsIn = List(Episode.NEWHOPE, Episode.EMPIRE, Episode.JEDI), 66 | homePlanet = Some("Alderaan")), 67 | Human( 68 | id = "1004", 69 | name = Some("Wilhuff Tarkin"), 70 | friends = List("1001"), 71 | appearsIn = List(Episode.NEWHOPE, Episode.EMPIRE, Episode.JEDI), 72 | homePlanet = None) 73 | ) 74 | 75 | val droids = List( 76 | Droid( 77 | id = "2000", 78 | name = Some("C-3PO"), 79 | friends = List("1000", "1002", "1003", "2001"), 80 | appearsIn = List(Episode.NEWHOPE, Episode.EMPIRE, Episode.JEDI), 81 | primaryFunction = Some("Protocol")), 82 | Droid( 83 | id = "2001", 84 | name = Some("R2-D2"), 85 | friends = List("1000", "1002", "1003"), 86 | appearsIn = List(Episode.NEWHOPE, Episode.EMPIRE, Episode.JEDI), 87 | primaryFunction = Some("Astromech")) 88 | ) 89 | } 90 | -------------------------------------------------------------------------------- /src/main/scala/SchemaDefinition.scala: -------------------------------------------------------------------------------- 1 | import sangria.execution.deferred.{Fetcher, HasId} 2 | import sangria.schema._ 3 | 4 | import scala.concurrent.Future 5 | 6 | /** 7 | * Defines a GraphQL schema for the current project 8 | */ 9 | object SchemaDefinition { 10 | /** 11 | * Resolves the lists of characters. These resolutions are batched and 12 | * cached for the duration of a query. 13 | */ 14 | val characters: Fetcher[CharacterRepo, Character with Product with Serializable, Character with Product with Serializable, String] = Fetcher.caching( 15 | (ctx: CharacterRepo, ids: Seq[String]) => 16 | Future.successful(ids.flatMap(id => ctx.getHuman(id) orElse ctx.getDroid(id))))(HasId(_.id)) 17 | 18 | val EpisodeEnum: EnumType[Episode.Value] = EnumType( 19 | "Episode", 20 | Some("One of the films in the Star Wars Trilogy"), 21 | List( 22 | EnumValue("NEWHOPE", 23 | value = Episode.NEWHOPE, 24 | description = Some("Released in 1977.")), 25 | EnumValue("EMPIRE", 26 | value = Episode.EMPIRE, 27 | description = Some("Released in 1980.")), 28 | EnumValue("JEDI", 29 | value = Episode.JEDI, 30 | description = Some("Released in 1983.")))) 31 | 32 | val Character: InterfaceType[CharacterRepo, Character] = 33 | InterfaceType( 34 | "Character", 35 | "A character in the Star Wars Trilogy", 36 | () => fields[CharacterRepo, Character]( 37 | Field("id", StringType, 38 | Some("The id of the character."), 39 | resolve = _.value.id), 40 | Field("name", OptionType(StringType), 41 | Some("The name of the character."), 42 | resolve = _.value.name), 43 | Field("friends", ListType(Character), 44 | Some("The friends of the character, or an empty list if they have none."), 45 | resolve = ctx => characters.deferSeqOpt(ctx.value.friends)), 46 | Field("appearsIn", OptionType(ListType(OptionType(EpisodeEnum))), 47 | Some("Which movies they appear in."), 48 | resolve = _.value.appearsIn map (e => Some(e))) 49 | )) 50 | 51 | val Human: ObjectType[CharacterRepo, Human] = 52 | ObjectType( 53 | "Human", 54 | "A humanoid creature in the Star Wars universe.", 55 | interfaces[CharacterRepo, Human](Character), 56 | fields[CharacterRepo, Human]( 57 | Field("id", StringType, 58 | Some("The id of the human."), 59 | resolve = _.value.id), 60 | Field("name", OptionType(StringType), 61 | Some("The name of the human."), 62 | resolve = _.value.name), 63 | Field("friends", ListType(Character), 64 | Some("The friends of the human, or an empty list if they have none."), 65 | resolve = ctx => characters.deferSeqOpt(ctx.value.friends)), 66 | Field("appearsIn", OptionType(ListType(OptionType(EpisodeEnum))), 67 | Some("Which movies they appear in."), 68 | resolve = _.value.appearsIn map (e => Some(e))), 69 | Field("homePlanet", OptionType(StringType), 70 | Some("The home planet of the human, or null if unknown."), 71 | resolve = _.value.homePlanet) 72 | )) 73 | 74 | val Droid: ObjectType[CharacterRepo, Droid] = ObjectType( 75 | "Droid", 76 | "A mechanical creature in the Star Wars universe.", 77 | interfaces[CharacterRepo, Droid](Character), 78 | fields[CharacterRepo, Droid]( 79 | Field("id", StringType, 80 | Some("The id of the droid."), 81 | resolve = _.value.id), 82 | Field("name", OptionType(StringType), 83 | Some("The name of the droid."), 84 | resolve = ctx => Future.successful(ctx.value.name)), 85 | Field("friends", ListType(Character), 86 | Some("The friends of the droid, or an empty list if they have none."), 87 | resolve = ctx => characters.deferSeqOpt(ctx.value.friends)), 88 | Field("appearsIn", OptionType(ListType(OptionType(EpisodeEnum))), 89 | Some("Which movies they appear in."), 90 | resolve = _.value.appearsIn map (e => Some(e))), 91 | Field("primaryFunction", OptionType(StringType), 92 | Some("The primary function of the droid."), 93 | resolve = _.value.primaryFunction) 94 | )) 95 | 96 | val ID: Argument[String] = Argument("id", StringType, description = "id of the character") 97 | 98 | val EpisodeArg: Argument[Option[Episode.Value]] = Argument("episode", OptionInputType(EpisodeEnum), 99 | description = "If omitted, returns the hero of the whole saga. If provided, returns the hero of that particular episode.") 100 | 101 | val LimitArg: Argument[Int] = Argument("limit", OptionInputType(IntType), defaultValue = 20) 102 | val OffsetArg: Argument[Int] = Argument("offset", OptionInputType(IntType), defaultValue = 0) 103 | 104 | val Query: ObjectType[CharacterRepo, Unit] = ObjectType( 105 | "Query", fields[CharacterRepo, Unit]( 106 | Field("hero", Character, 107 | arguments = EpisodeArg :: Nil, 108 | deprecationReason = Some("Use `human` or `droid` fields instead"), 109 | resolve = ctx => ctx.ctx.getHero(ctx.arg(EpisodeArg))), 110 | Field("human", OptionType(Human), 111 | arguments = ID :: Nil, 112 | resolve = ctx => ctx.ctx.getHuman(ctx arg ID)), 113 | Field("droid", Droid, 114 | arguments = ID :: Nil, 115 | resolve = ctx => ctx.ctx.getDroid(ctx arg ID).get), 116 | Field("humans", ListType(Human), 117 | arguments = LimitArg :: OffsetArg :: Nil, 118 | resolve = ctx => ctx.ctx.getHumans(ctx arg LimitArg, ctx arg OffsetArg)), 119 | Field("droids", ListType(Droid), 120 | arguments = LimitArg :: OffsetArg :: Nil, 121 | resolve = ctx => ctx.ctx.getDroids(ctx arg LimitArg, ctx arg OffsetArg)) 122 | )) 123 | 124 | val StarWarsSchema: Schema[CharacterRepo, Unit] = Schema(Query) 125 | } 126 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | --------------------------------------------------------------------------------