Skip to main content

Schema Plugins — Graphile BuildSchema 插件 — Graphile Build

The PostGraphile GraphQL schema is constructed out of a number of Graphile Build plugins. The core PG-related plugins can be found here:

PostGraphile 的 GraphQL schema 由一系列 Graphile Build 插件共同构建而成。核心 PostgreSQL 相关插件的源码位于:

These plugins introduce small amounts of functionality, and build upon each other. The default list of plugins can be found from the defaultPlugins export in src/preset.ts of the graphile-build-pg module.

每个插件只负责一小块职责,彼此层层叠加。默认的插件列表可以在 graphile-build-pg 模块 src/preset.ts 文件导出的 defaultPlugins 中查看。

You can extend PostGraphile’s GraphQL schema by adding plugins or presets. You may even opt to replace the entire list of plugins used to build the schema. Graphile Build plugins are built on top of the GraphQL reference JS implementation, so it is recommended that you have familiarity with that before attempting to write your own plugins.

你可以通过添加插件或 preset 来扩展 PostGraphile 的 GraphQL schema,甚至可以完全替换掉用于构建 schema 的整套插件列表。由于 Graphile Build 插件构建在 GraphQL 官方 JS 参考实现之上,建议在自行编写插件前先对其有所了解。

Adding root query/mutation fields添加根 Query/Mutation 字段​

A common request is to add additional root-level fields to your schema, for example to integrate external services. The easiest way to do this is to use extendSchema to generate a plugin that will extend your schema (this can be used to add fields anywhere, not just at the root-level):

向 schema 添加额外的根级字段是一个非常普遍的需求(例如用来集成外部服务)。最简单的方式是使用 extendSchema 来生成扩展插件(不仅限于根级字段,它可以向任意位置添加字段):

add-http-bin-plugin.js
import { extendSchema } from "postgraphile/utils";
import { loadOne } from "postgraphile/grafast";
import fetch from "node-fetch";

export default extendSchema({
typeDefs: /* GraphQL */ `
extend type Query {
httpBinHeaders: JSON
}
`,
objects: {
Query: {
plans: {
httpBinHeaders() {
return loadOne(null, async () => {
const response = await fetch("https://httpbin.org/headers");
return response.json();
});
},
},
},
},
});

If you need to do this using the low-level plugins API for some reason (for example you’re defining the fields in a more automated way) then you can use a ‘GraphQLObjectType_fields’ hook and to add our new field:

如果出于某些原因(例如需要以更自动化的方式批量生成字段)必须使用底层插件 API,你可以通过 GraphQLObjectType_fields hook 来添加新字段:

add-http-bin-plugin-raw.js
import fetch from "node-fetch";

const AddHttpBinPlugin = {
name: "AddHttpBinPlugin",
version: "0.0.0",

schema: {
hooks: {
GraphQLObjectType_fields(
fields, // Input object - the fields for this GraphQLObjectType
build, // Build object - handy utils
context, // Context object - used for filtering
) {
const {
extend,
getTypeByName,
grafast: { loadOne },
options: { jsonScalarAsString },
} = build;
const {
scope: { isRootQuery },
} = context;
if (!isRootQuery) {
// This isn't the object we want to modify:
// return the input object unmodified
return fields;
}

// We don't want to introduce a new JSON type as that will clash,
// so let's find the JSON type that other fields use:
const JSONType = getTypeByName("JSON");

return extend(fields, {
httpBinHeaders: {
type: JSONType,
plan() {
return loadOne(null, async () => {
const response = await fetch("https://httpbin.org/headers");
if (jsonScalarAsString) {
// We've been told to provide JSON scalars in stringified format
return response.text();
} else {
// By default, we can just return a dynamic "JSON" scalar
return response.json();
}
});
},
},
});
},
},
},
};

export default AddHttpBinPlugin;

(If you wanted to add a mutation you’d use isRootMutation rather than isRootQuery.)

(如果要添加 mutation 字段,只需将 isRootQuery 替换为 isRootMutation。)

We can then load our plugin into PostGraphile by adding it to our preset:

随后,把编写好的插件加入 preset 即可加载到 PostGraphile 中:

graphile.config.mjs
import AddHttpBinPlugin from "./add-http-bin-plugin.js";

export default {
// ...
plugins: [AddHttpBinPlugin],
};

Note that the types of added fields can use standard GraphQL objects in addition to types generated via the Graphile Build system. (However, if you do not build your object types via Graphile Build’s registerObjectType (or similar) then the objects referenced cannot be extended via plugins.)

注意,新增字段的类型既可以使用 Graphile Build 系统生成的类型,也可以使用标准的 GraphQL 对象类型。(不过,如果不是通过 Graphile Build 的 registerObjectType 或类似方式构建的对象类型,所引用的对象将无法再通过插件进行扩展。)

Removing things from the schema从 schema 中移除内容​

If you’re looking for an easy way to prevent certain tables, fields, functions or relations being added to your GraphQL schema, check out smart comments.

如果你只是想便捷地阻止特定表、字段、函数或 relation 被添加到 GraphQL schema 中,请参阅 smart comments。

If you want to prevent a class of things from being added to the schema then you can disable the plugin that adds them; for example if you didn’t want Postgres functions added you could disable PgCustomTypeFieldPlugin:

如果你想屏蔽某一整类元素进入 schema,可以直接禁用负责生成它们的插件。例如,不希望把 Postgres 函数暴露到 schema 中时,可以禁用 PgCustomTypeFieldPlugin:

graphile.config.mjs
export default {
// ...
disabledPlugins: ["PgCustomTypeFieldPlugin"],
};
It's more efficient to stop generation than to remove fields later从源头阻止生成比事后移除字段更高效

For efficiency’s sake, it’s advised that rather than removing things from the schema, you instead avoid them being generated in the first place using the tips above.

出于性能考虑,建议优先采用上述方法从源头避免生成不需要的元素,而不是等生成后再将其从 schema 中剔除。

However, sometimes the above strategies don’t allow you to make the changes you desire. To remove something manually, you need to add a hook to the thing that owns the thing you wish to remove — for example if you want to remove a field bar from an object type Foo you could hook GraphQLObjectType_fields and return the set of fields less the one you want removed.

但有时上述策略无法精确满足需求。要手动移除某项内容,需要为其所属的父级对象添加 hook——例如,若想从对象类型 Foo 中移除字段 bar,可以挂载 GraphQLObjectType_fields hook,并在返回字段集合时剔除该字段。

Here’s an example of a plugin generator you could use to generate plugins to remove individual fields. This is just to demonstrate how a plugin to do this might work, smart comments are likely a better approach.

下面这个插件生成器示例演示了如何动态创建用于移除单个字段的插件。该示例仅用于说明实现原理,实际场景中通常使用 smart comments 会更合适。

function removeField(
objectName: string,
fieldName: string,
): GraphileConfig.Plugin {
return {
name: `RemoveField_${objectName}_${fieldName}_Plugin`,
description: `Removes the ${objectName}.${fieldName} field from the GraphQL schema`,
version: "0.0.0",

schema: {
hooks: {
GraphQLObjectType_fields(fields, build, context) {
if (context.Self.name !== objectName) return fields;
delete fields[fieldName];
return fields;
},
},
},
};
}

export const RemoveFooDotBarPlugin = removeField("Foo", "bar");