graphql/express-graphql

Name: express-graphql

Owner: Facebook GraphQL

Description: Create a GraphQL HTTP server with Express.

Created: 2015-08-04 23:29:53.0

Updated: 2018-05-24 16:41:28.0

Pushed: 2018-05-09 16:20:51.0

Homepage: null

Size: 627

Language: JavaScript

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

GraphQL HTTP Server Middleware

Build Status Coverage Status

Create a GraphQL HTTP server with any HTTP web framework that supports connect styled middleware, including Connect itself, Express and Restify.

Installation
install --save express-graphql
Simple Setup

Just mount express-graphql as a route handler:

t express = require('express');
t graphqlHTTP = require('express-graphql');

t app = express();

use('/graphql', graphqlHTTP({
hema: MyGraphQLSchema,
aphiql: true


listen(4000);
Setup with Restify

Use .get or .post (or both) rather than .use to configure your route handler. If you want to show GraphiQL in the browser, set graphiql: true on your .get handler.

t restify = require('restify');
t graphqlHTTP = require('express-graphql');

t app = restify.createServer();

post('/graphql', graphqlHTTP({
hema: MyGraphQLSchema,
aphiql: false


get('/graphql', graphqlHTTP({
hema: MyGraphQLSchema,
aphiql: true


listen(4000);
Options

The graphqlHTTP function accepts the following options:

In addition to an object defining each option, options can also be provided as a function (or async function) which returns this options object. This function is provided the arguments (request, response, graphQLParams) and is called after the request has been parsed.

The graphQLParams is provided as the object { query, variables, operationName, raw }.

use('/graphql', graphqlHTTP(async (request, response, graphQLParams) => ({
hema: MyGraphQLSchema,
otValue: await someFunctionToGetRootValue(request),
aphiql: true
;
HTTP Usage

Once installed at a path, express-graphql will accept requests with the parameters:

GraphQL will first look for each parameter in the URL's query-string:

phql?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 a previous middleware has already parsed the POST body, the request.body value will be used. Use multer or a similar middleware to add support for multipart/form-data content, which may be useful for GraphQL mutations involving uploading files. See an example using multer.

If the POST body has not yet been parsed, express-graphql will interpret it depending on the provided Content-Type header.

Combining with Other Express Middleware

By default, the express request is passed as the GraphQL context. Since most express middleware operates by adding extra data to the request object, this means you can use most express middleware just by inserting it before graphqlHTTP is mounted. This covers scenarios such as authenticating the user, handling file uploads, or mounting GraphQL on a dynamic endpoint.

This example uses express-session to provide GraphQL with the currently logged-in session.

t session = require('express-session');
t graphqlHTTP = require('express-graphql');

t app = express();

use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}));

use('/graphql', graphqlHTTP({
hema: MySessionAwareGraphQLSchema,
aphiql: true

Then in your type definitions, you can access the request via the third “context” argument in your resolve function:

GraphQLObjectType({
me: 'MyType',
elds: {
myField: {
  type: GraphQLString,
  resolve(parentValue, args, request) {
    // use `request.session` here
  }
}


Providing Extensions

The GraphQL response allows for adding additional information in a response to a GraphQL query via a field in the response called "extensions". This is added by providing an extensions function when using graphqlHTTP. The function must return a JSON-serializable Object.

When called, this is provided an argument which you can use to get information about the GraphQL request:

{ document, variables, operationName, result }

This example illustrates adding the amount of time consumed by running the provided query, which could perhaps be used by your development tools.

t graphqlHTTP = require('express-graphql');

t app = express();

use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}));

use('/graphql', graphqlHTTP(request => {
nst startTime = Date.now();
turn {
schema: MyGraphQLSchema,
graphiql: true,
extensions({ document, variables, operationName, result }) {
  return { runTime: Date.now() - startTime };
}


When querying this endpoint, it would include this information in the result, for example:


ata": { ... }
xtensions": {
"runTime": 135


Additional Validation Rules

GraphQL's validation phase checks the query to ensure that it can be successfully executed against the schema. The validationRules option allows for additional rules to be run during this phase. Rules are applied to each node in an AST representing the query using the Visitor pattern.

A validation rule is a function which returns a visitor for one or more node Types. Below is an example of a validation preventing the specific fieldname metadata from being queried. For more examples see the specifiedRules in the graphql-js package.

rt { GraphQLError } from 'graphql';

rt function DisallowMetadataQueries(context) {
turn {
Field(node) {
  const fieldName = node.name.value;

  if (fieldName === "metadata") {
    context.reportError(
      new GraphQLError(
        `Validation: Requesting the field ${fieldName} is not allowed`,
      ),
    );
  }
}


Other Exports

getGraphQLParams(request: Request): Promise<GraphQLParams>

Given an HTTP Request, this returns a Promise for the parameters relevant to running a GraphQL request. This function is used internally to handle the incoming request, you may use it directly for building other similar services.

t graphqlHTTP = require('express-graphql');

hqlHTTP.getGraphQLParams(request).then(params => {
 do something...

Debugging Tips

During development, it's useful to get more information from errors, such as stack traces. Providing a function to formatError enables this:

atError: error => ({
ssage: error.message,
cations: error.locations,
ack: error.stack ? error.stack.split('\n') : [],
th: error.path


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.