graphql-api-koa

GraphQL execution and error handling middleware written from scratch for Koa.

Usage no npm install needed!

<script type="module">
  import graphqlApiKoa from 'https://cdn.skypack.dev/graphql-api-koa';
</script>

README

graphql-api-koa logo

graphql-api-koa

npm version CI status

GraphQL execution and error handling middleware written from scratch for Koa.

Setup

To install graphql-api-koa and the graphql peer dependency with npm, run:

npm install graphql-api-koa graphql

See the execute middleware examples to get started.

API

Table of contents

function errorHandler

Creates Koa middleware to handle errors. Use this before other middleware to catch all errors for a correctly formatted GraphQL response.

Special Koa middleware error properties can be used to determine how the error appears in the response payload errors array and the response HTTP status code.

Special GraphQL resolver error properties can be used to determine how the error appears in the response payload errors array.

Additional custom Koa middleware can be used to customize the response.

Returns: Function — Koa middleware.

Examples

Ways to import.

import { errorHandler } from 'graphql-api-koa';
import errorHandler from 'graphql-api-koa/public/errorHandler.mjs';

function execute

Creates Koa middleware to execute GraphQL. Use after the errorHandler and body parser middleware.

Parameter Type Description
options ExecuteOptions Options.

Returns: Function — Koa middleware.

Examples

Ways to import.

import { execute } from 'graphql-api-koa';
import execute from 'graphql-api-koa/public/execute.mjs';

A basic GraphQL API.

import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import { errorHandler, execute } from 'graphql-api-koa';
import schema from './schema.mjs';

const app = new Koa()
  .use(errorHandler())
  .use(
    bodyParser({
      extendTypes: {
        json: 'application/graphql+json',
      },
    })
  )
  .use(execute({ schema }));

type ErrorGraphQLResolver

A GraphQL resolver error may have these special properties for the errorHandler Koa middleware to use to determine how the error appears in the response payload errors array.

Type: object

Property Type Description
message string Error message. If the error expose property isn’t true, the message is replaced with Internal Server Error in the response payload errors array.
extensions object<string, *>? A map of custom error data that is exposed to the client in the response payload errors array, regardless of the error expose or status properties.
expose boolean? Should the original error message be exposed to the client.

See

Examples

An error thrown in a GraphQL resolver, exposed to the client.

Query:

{
  user(handle: "jaydenseric") {
    name
    email
  }
}

Error thrown in the User.email resolver:

const error = new Error('Unauthorized access to user data.');
error.expose = true;

Response has a 200 HTTP status code, with this payload:

{
  "errors": [
    {
      "message": "Unauthorized access to user data.",
      "locations": [{ "line": 4, "column": 5 }],
      "path": ["user", "email"]
    }
  ],
  "data": {
    "user": {
      "name": "Jayden Seric",
      "email": null
    }
  }
}

type ErrorKoaMiddleware

A Koa middleware error may have these special properties for the errorHandler Koa middleware to use to determine how the error appears in the response payload errors array and the response HTTP status code.

Type: object

Property Type Description
message string Error message. If the error status property >= 500 or the error expose property isn’t true, the message is replaced with Internal Server Error in the response payload errors array.
extensions object<string, *>? A map of custom error data that is exposed to the client in the response payload errors array, regardless of the error expose or status properties.
status number? Determines the response HTTP status code.
expose boolean? Should the original error message be exposed to the client.

See

Examples

A client error thrown in Koa middleware.

Error constructed manually:

const error = new Error('Rate limit exceeded.');
error.extensions = {
  code: 'RATE_LIMIT_EXCEEDED',
};
error.status = 429;

Error constructed using http-errors:

import createHttpError from 'http-errors';

const error = createHttpError(429, 'Rate limit exceeded.', {
  extensions: {
    code: 'RATE_LIMIT_EXCEEDED',
  },
});

Response has a 429 HTTP status code, with this payload:

{
  "errors": [
    {
      "message": "Rate limit exceeded.",
      "extensions": {
        "code": "RATE_LIMIT_EXCEEDED"
      }
    }
  ]
}

A server error thrown in Koa middleware, not exposed to the client.

Error:

const error = new Error('Database connection failed.');

Response has a 500 HTTP status code, with this payload:

{
  "errors": [
    {
      "message": "Internal Server Error"
    }
  ]
}

A server error thrown in Koa middleware, exposed to the client.

Error:

const error = new Error('Service unavailable due to maintenance.');
error.status = 503;
error.expose = true;

Response has a 503 HTTP status code, with this payload:

{
  "errors": [
    {
      "message": "Service unavailable due to maintenance."
    }
  ]
}

type ExecuteOptions

execute Koa middleware options.

Type: object

Property Type Description
schema GraphQLSchema GraphQL schema.
validationRules Array? Validation rules for GraphQL.js validate, in addition to the default GraphQL.js specifiedRules.
rootValue *? Value passed to the first resolver.
contextValue *? Execution context (usually an object) passed to resolvers.
fieldResolver Function? Custom default field resolver.
execute Function? Replacement for GraphQL.js execute.
override ExecuteOptionsOverride? Override any ExecuteOptions (except override) per request.

Examples

execute middleware options that sets the schema once but populates the user in the GraphQL context from the Koa context each request.

import schema from './schema.mjs';

const executeOptions = {
  schema,
  override: (ctx) => ({
    contextValue: {
      user: ctx.state.user,
    },
  }),
};

type ExecuteOptionsOverride

Overrides any ExecuteOptions (except override) per request.

Type: Function

Parameter Type Description
context object Koa context.

Returns: object — execute middleware options subset.

Examples

An execute middleware options override that populates the user in the GraphQL context from the Koa request context.

const executeOptionsOverride = (ctx) => ({
  contextValue: {
    user: ctx.state.user,
  },
});