Skip to main content

processSchema

This plugin enables a way of processing the schema after it’s built.

该插件用于在 GraphQL schema 构建完成后对其进行后续处理。

Use cases include:

常见应用场景包括:

  • Printing the schema SDL to a file

    将 schema SDL 输出到文件

  • Uploading the schema SDL to a network service

    将 schema SDL 上传至远程网络服务

  • Checking the schema against your persisted queries

    对照持久化查询(persisted queries)校验 schema

  • Validating the schema against your custom logic

    按照自定义规则校验 schema

  • Exporting the executable schema (in JavaScript) to a file

    将可执行的 schema(以 JavaScript 形式)导出到文件

  • Replacing the schema with a mocked version or a derivative version (e.g. stitching it with another schema)

    将 schema 替换为 mock 版本或衍生版本(例如与其他 schema 进行拼接)

  • Integrating with third-party libraries

    与第三方库集成

Signature函数签名​

function processSchema(
process: (schema: GraphQLSchema) => GraphQLSchema,
): GraphileConfig.Plugin;

The plugin accepts one argument: a schema processing function which will be called with the generated schema and must either return the same schema (e.g. if you’re doing a read-only operation, or mutating the schema directly) or return an alternative schema (typically a derivative).

该插件接收一个参数:一个 schema 处理函数。框架在生成 schema 后会调用该函数,并将生成的 schema 作为参数传入;该函数必须返回同一个 schema(例如执行只读检查,或直接原地修改 schema),或者返回一个替代的 schema(通常是基于原 schema 的衍生版本)。

How to do this asynchronously如何执行异步操作

The callback to this plugin operates synchronously. If you need to do asynchronous work then be sure to handle any errors that may occur, and note that the result of the asynchronous work will not affect the return result of this plugin (and thus the schema being used by your server).

传入该插件的回调函数必须同步执行。如果你需要在其中执行异步任务,请务必妥善捕获并处理可能发生的异常;同时要注意,异步任务的结果不会影响该插件的返回值(即不会影响服务器最终使用的 schema)。

Compatibility with third parties与第三方工具的兼容性

Because PostGraphile schemas use Grafast plan resolvers, third party tooling that manipulate traditional resolvers are likely to break the schema, and not achieve the goals set out. For example, graphql-shield is currently not compatible with Grafast plans.

由于 PostGraphile 生成的 schema 使用的是 Grafast plan resolver,那些基于传统 resolver 进行改造的第三方工具很可能会破坏 schema 结构,也无法达到预期效果。例如,graphql-shield 目前尚不兼容 Grafast 执行计划。

Example: exporting the schema as exportable code示例:将 schema 导出为可执行代码​

import { processSchema } from "postgraphile/utils";
import { exportSchema } from "graphile-export";

const ExportSchemaPlugin = processSchema((schema) => {
exportSchema(schema, `${process.cwd()}/exported-schema.mjs`, {
mode: "typeDefs",
}).catch((e) => {
console.error(e);
});
return schema;
});