当前位置: 首页 > 软件库 > 大数据 > 数据查询 >

graphql-api-koa

授权协议 Readme
开发语言 Java
所属分类 大数据、 数据查询
软件类型 开源软件
地区 不详
投 递 者 王彭薄
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

graphql-api-koa

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

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<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.

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 的查询语言 详解见:GraphQL入门   https://blog.csdn.net/future_challenger/article/details/54773541

  • 在之前翻译的一篇文章 为什么我们在 API 中使用 GraphQL 中介绍 GraphQL 的作用,之后笔者在 Koa 框架中实现相关接口及调用方式并整理相关实现过程,希望对如笔者一样想要使用 GraphQL 的入门者一些帮助。 由于笔者日常工作开发中使用的Node 后台框架是 Koa,因此就以此框架为基础实现 /graphql 接口,接下来会分步介绍实现的步骤与方法。 路由配置 建立一个路由配置

  • 客户端使用React + ApolloClient + GestaltUI 服务端使用Koa2 + GraphQL + Mongoose github 欢迎加⭐ github.com/tzuser/reac… 在线预览 在线预览 API 启动 cnpm install npm run start 复制代码 默认是连接远程服务器的,以下连接本地的服务 安装mongodb 更改 server/db.j

 相关资料
  • graphql-api graphql-api helps you implement a robust GraphQL API in Haskell. By the time a query makes it to your handler you are dealing with strong, static types that make sense for your problem dom

  • 使用REST,我们可以使用Swagger、RAML或其他技术来记录我们的API,并生成一个HTML文档,我们的消费者可以阅读该文档,而无需与服务器进行任何交互。 GraphQL是否存在类似的情况?是否有任何方法生成资源和属性的文档?

  • GraphQL/REST API Demo A demo of what an equivalent REST API and GraphQL API look like. This code is used in the first chapter of The GraphQL Guide by John Resig and Loren Sands-Ramshaw. Here's the Gra

  • Setup $ yarn install && open http://localhost:4000 && yarn run start Medium: https://medium.com/@wesharehoodies/how-to-setup-a-powerful-api-with-nodejs-graphql-mongodb-hapi-and-swagger-e251ac189649?

  • 我正在开发一个GraphQL API,其中有一个带有初步数据比较的导入特性(在现有数据之间 电流为: API使用者执行GQL查询查询预览导入($数据:字符串),其中,是base64编码的电子表格。在后端解析数据,并在数据库中插入一条guid为的记录。最后,API返回电子表格中的数据与数据库中的数据以及guid之间的差异结果 前端然后要求用户在看到比较(创建、更新、删除)后确认导入。为此,向API发