gak

graphql-api-koa

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

Showing:

Popularity

Downloads/wk

159

GitHub Stars

51

Maintenance

Last Commit

5mos ago

Contributors

0

Package

Dependencies

2

Size (min+gzip)

3.7KB

License

MIT

Type Definitions

Tree-Shakeable

No?

Categories

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.

ParameterTypeDescription
optionsExecuteOptionsOptions.

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

PropertyTypeDescription
messagestringError message. If the error expose property isn’t true, the message is replaced with Internal Server Error in the response payload errors array.
extensionsobject<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.
exposeboolean?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

PropertyTypeDescription
messagestringError 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.
extensionsobject<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.
statusnumber?Determines the response HTTP status code.
exposeboolean?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

PropertyTypeDescription
schemaGraphQLSchemaGraphQL schema.
validationRulesArray?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.
fieldResolverFunction?Custom default field resolver.
executeFunction?Replacement for GraphQL.js execute.
overrideExecuteOptionsOverride?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

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

Rate & Review

Great Documentation0
Easy to Use0
Performant0
Highly Customizable0
Bleeding Edge0
Responsive Maintainers0
Poor Documentation0
Hard to Use0
Slow0
Buggy0
Abandoned0
Unwelcoming Community0
100