Create a GraphQL HTTP server with Koa.
Usage with Koa-Router
1 | const Koa = require('koa') |
Options
The GraphqlHTTP
function accpets the following options:
schema
: AGraphQLSchema
instance fromgraphql.js
, required.graphiql
: Iftrue
, presetns GraphiQL when the route with a/graphiql
appended is loaded in a browser. We recommended that you setgraphiql
toture
when your app is in development, because it’s quite useful. You may or may not want it in production.rootValue
: A value to pass as therootValue
to thegraphql()
function fromgraphql.js
context
: A value to pass as thecontext
to thegraphql()
function fromgraphql.js
. Ifcontext
is not provided, thectx
object is passes as the context.pretty
: Iftrue
, any JSON response will be pretty-printed.formatError
: An optional function which will be used to format any errors produced by fulfilling a GraphQL operation. If no function is provided, GraphQL’s default spec-compliantformatError
function will be used.extensions
: An optional function for adding additional metadata to the GraphQL response as a key-value object. The result will be added toextensions
field in the resulting JSON. This is often useful place to add development time metadata such as the runtime of a query or the amount of resources consumed. This may be an async function. The function is given one object as an argument:{ document, variables, operationName, result }
validationRules
: Optional additional validation rules queries must satisfy in addition to those defined by the GraphQL spec.
HTTP Usage
Once installed at a path, koa-graphql
will accept requests with the parameters:
query
: A string GraphQL document to be executed.variables
: The runtime values to use for any GraphQL query variables as a JSON object.operationName
: If the providedquery
contains mutiple named operations, this specifies which operation should be executed. If not provided, a 400 error will be returned if thequery
contains multiple named operations.raw
: If thegraphql
option is enabled and theraw
parameter is provided raw JSON will always be returned instead of GraphQL even when loaded from a browser.
GraphQL will first look for each parameter in the URL’s query-string:
/graphql?query=query+getUser($id:ID){user(id:$id){name}}&variables={"id":"4"}
If not found in the query-string, it will look in the POST request body.
If the POST body has not been parsed, koa-graphql will interpret it depending on the provided Contetn-Type header:
application/json
: the POST body will be parsed as a JSON object.application/x-www-form-urlencoded
: this POST body will be parsed as a url-encoded string of key-value pairs.application/graphql
: The POST body will be parsed as GraphQL query string, which provides thequery
parameter.