GithubHelp home page GithubHelp logo

vladshcherbin / graphql-api-koa Goto Github PK

View Code? Open in Web Editor NEW

This project forked from jaydenseric/graphql-api-koa

0.0 0.0 0.0 325 KB

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

Home Page: https://npm.im/graphql-api-koa

JavaScript 100.00%

graphql-api-koa's Introduction

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

graphql-api-koa's People

Contributors

jaydenseric avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.