• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

jaydenseric/graphql-api-koa: GraphQL execution and error handling middleware wri ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

jaydenseric/graphql-api-koa

开源软件地址:

https://github.com/jaydenseric/graphql-api-koa

开源编程语言:

JavaScript 100.0%

开源软件介绍:

graphql-api-koa logo

graphql-api-koa

npm version CI status

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

Installation

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

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

How to import.

import errorHandler from "graphql-api-koa/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

How to import.

import execute from "graphql-api-koa/execute.mjs";

A basic GraphQL API.

import Koa from "koa";
import bodyParser from "koa-bodyparser";
import errorHandler from "graphql-api-koa/errorHandler.mjs";
import execute from "graphql-api-koa/execute.mjs";
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 Record<string, any>? 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 Record<string, any>? 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<Function>? Validation rules for GraphQL.js validate, in addition to the default GraphQL.js specifiedRules.
rootValue any? Value passed to the first resolver.
contextValue any? 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,
  },
});



鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap