graphql-community / koa-graphql

Create a GraphQL HTTP server with Koa.
MIT License
843 stars 61 forks source link
graphql koa koa-graphql koa-middleware

GraphQL Koa Middleware

npm version Build Status Coverage Status

Create a GraphQL HTTP server with Koa.

Port from express-graphql.

Installation

npm install --save koa-graphql

TypeScript

This module includes a TypeScript declaration file to enable auto complete in compatible editors and type information for TypeScript projects.

Simple Setup

Mount koa-graphql as a route handler:

const Koa = require('koa');
const mount = require('koa-mount');
const { graphqlHTTP } = require('koa-graphql');

const app = new Koa();

app.use(
  mount(
    '/graphql',
    graphqlHTTP({
      schema: MyGraphQLSchema,
      graphiql: true,
    }),
  ),
);

app.listen(4000);

Setup with Koa Router

With @koa/router:

const Koa = require('koa');
const Router = require('@koa/router');
const { graphqlHTTP } = require('koa-graphql');

const app = new Koa();
const router = new Router();

router.all(
  '/graphql',
  graphqlHTTP({
    schema: MyGraphQLSchema,
    graphiql: true,
  }),
);

app.use(router.routes()).use(router.allowedMethods());

Setup with Koa v1

For Koa 1, use koa-convert to convert the middleware:

const koa = require('koa');
const mount = require('koa-mount'); // koa-mount@1.x
const convert = require('koa-convert');
const { graphqlHTTP } = require('koa-graphql');

const app = koa();

app.use(
  mount(
    '/graphql',
    convert.back(
      graphqlHTTP({
        schema: MyGraphQLSchema,
        graphiql: true,
      }),
    ),
  ),
);

Setup with Subscription Support

const Koa = require('koa');
const mount = require('koa-mount');
const { graphqlHTTP } = require('koa-graphql');
const typeDefs = require('./schema');
const resolvers = require('./resolvers');
const { makeExecutableSchema } = require('graphql-tools');
const schema = makeExecutableSchema({
  typeDefs: typeDefs,
  resolvers: resolvers,
});
const { execute, subscribe } = require('graphql');
const { createServer } = require('http');
const { SubscriptionServer } = require('subscriptions-transport-ws');
const PORT = 4000;
const app = new Koa();
app.use(
  mount(
    '/graphql',
    graphqlHTTP({
      schema: schema,
      graphiql: {
        subscriptionEndpoint: `ws://localhost:${PORT}/subscriptions`,
      },
    }),
  ),
);
const ws = createServer(app.callback());
ws.listen(PORT, () => {
  // Set up the WebSocket for handling GraphQL subscriptions.
  new SubscriptionServer(
    {
      execute,
      subscribe,
      schema,
    },
    {
      server: ws,
      path: '/subscriptions',
    },
  );
});

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 }.

app.use(
  mount(
    '/graphql',
    graphqlHTTP(async (request, response, ctx, graphQLParams) => ({
      schema: MyGraphQLSchema,
      rootValue: await someFunctionToGetRootValue(request),
      graphiql: true,
    })),
  ),
);

HTTP Usage

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

GraphQL will first look for each parameter in the query string of a URL:

/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 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, koa-graphql will interpret it depending on the provided Content-Type header.

Combining with Other koa Middleware

By default, the koa request is passed as the GraphQL context. Since most koa middleware operates by adding extra data to the request object, this means you can use most koa 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 koa-session to provide GraphQL with the currently logged-in session.

const Koa = require('koa');
const mount = require('koa-mount');
const session = require('koa-session');
const { graphqlHTTP } = require('koa-graphql');

const app = new Koa();
app.keys = ['some secret'];
app.use(session(app));
app.use(function* (next) {
  this.session.id = 'me';
  yield next;
});

app.use(
  mount(
    '/graphql',
    graphqlHTTP({
      schema: MySessionAwareGraphQLSchema,
      graphiql: true,
    }),
  ),
);

Then in your type definitions, you can access the ctx via the third "context" argument in your resolve function:

new GraphQLObjectType({
  name: 'MyType',
  fields: {
    myField: {
      type: GraphQLString,
      resolve(parentValue, args, ctx) {
        // use `ctx.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, context }

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

const { graphqlHTTP } = require('koa-graphql');

const app = new Koa();

const extensions = ({
  document,
  variables,
  operationName,
  result,
  context,
}) => {
  return {
    runTime: Date.now() - context.startTime,
  };
};

app.use(
  mount(
    '/graphql',
    graphqlHTTP((request) => {
      return {
        schema: MyGraphQLSchema,
        context: { startTime: Date.now() },
        graphiql: true,
        extensions,
      };
    }),
  ),
);

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

{
  "data": { ... },
  "extensions": {
    "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 field name metadata from being queried. For more examples, see the specifiedRules in the graphql-js package.

import { GraphQLError } from 'graphql';

export function DisallowMetadataQueries(context) {
  return {
    Field(node) {
      const fieldName = node.name.value;

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

Disabling Introspection

Disabling introspection does not reflect best practices and does not necessarily make your application any more secure. Nevertheless, disabling introspection is possible by utilizing the NoSchemaIntrospectionCustomRule provided by the graphql-js package.

import { NoSchemaIntrospectionCustomRule } from 'graphql';

app.use(
  mount(
    '/graphql',
    graphqlHTTP((request) => {
      return {
        schema: MyGraphQLSchema,
        validationRules: [NoSchemaIntrospectionCustomRule],
      };
    }),
  ),
);

Custom GraphiQL Themes

To use custom GraphiQL theme you should pass to graphiql option an object with the property editorTheme. It could be a string with the name of a theme from CodeMirror

router.all(
  '/graphql',
  graphqlHTTP({
    schema: MyGraphQLSchema,
    graphiql: {
      editorTheme: 'blackboard',
    },
  }),
);

List of available CodeMirror themes

or an object with url and name properties where url should lead to your custom theme and name would be passed to the GraphiQL react element on creation as the editorTheme property

router.all(
  '/graphql',
  graphqlHTTP({
    schema: MyGraphQLSchema,
    graphiql: {
      editorTheme: {
        name: 'blackboard',
        url: 'https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.53.2/theme/erlang-dark.css',
      },
    },
  }),
);

For details see the GraphiQL spec

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 field name metadata from being queried. For more examples see the specifiedRules in the graphql-js package.

import { GraphQLError } from 'graphql';

export function DisallowMetadataQueries(context) {
  return {
    Field(node) {
      const fieldName = node.name.value;

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

Debugging Tips

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

customFormatErrorFn: (error, ctx) => ({
  message: error.message,
  locations: error.locations,
  stack: error.stack ? error.stack.split('\n') : [],
  path: error.path,
});

Examples

Other Relevant Projects

Please checkout awesome-graphql.

Contributing

Welcome pull requests!

License

MIT