Skip to content
master
Go to file
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

readme.md

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 graphql from 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.js';

Ways to require.

const { errorHandler } = require('graphql-api-koa');
const errorHandler = require('graphql-api-koa/public/errorHandler');

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.js';

Ways to require.

const { execute } = require('graphql-api-koa');
const execute = require('graphql-api-koa/public/execute');

A basic GraphQL API.

const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const { errorHandler, execute } = require('graphql-api-koa');
const schema = require('./schema');

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:

const createHttpError = require('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<Function>? 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.

const schema = require('./schema');

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,
  },
});

About

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

Topics

Resources

You can’t perform that action at this time.