Skip to main content

GraphQL Schema Plugins

PostGraphile’s schema generator is built from a number of graphile-build plugins. You can write your own plugins — either using the helpers available in graphile-utils, or using the raw plugin interface available from Graphile Build.

PostGraphile 的 schema 生成器由一系列 graphile-build 插件构建而成。你可以编写自己的插件——既可以使用 graphile-utils 提供的辅助工具,也可以直接使用 Graphile Build 暴露的底层插件接口。

Start with extendSchema()从 extendSchema() 入手

If you just want to add a few specific fields or types to your schema from JavaScript/TypeScript, extendSchema() will get you there quickly using GraphQL's ergonomic type extension SDL and Grafast's plan resolvers.

如果你只是想通过 JavaScript/TypeScript 向 schema 中添加几个特定字段或类型,extendSchema() 借助 GraphQL 简洁的类型扩展 SDL 与 Grafast 的 plan resolver,能让你快速完成扩展。

If, however, you want to make more far-reaching programatic changes to your schema, read on.

不过,如果你希望以编程方式对 schema 进行更深入、更广泛的调整,请继续往下阅读。

If you’re looking for an easy way to remove/rename things, check out smart tags.

如果你只是想用简单的方式移除或重命名某些元素,请参阅 smart tags。

Inflection exampleInflection 示例​

Here’s an example of a simple plugin which uses the “inflection” system to rename all database columns named full_name to be output as name in GraphQL:

下面是一个简单插件的示例,它借助“inflection”命名推导系统,将数据库中所有名为 full_name 的列在 GraphQL 中输出为 name:

/** @type {GraphileConfig.Plugin} */
const FullNameToNamePlugin = {
name: "FullNameToNamePlugin",
inflection: {
replace: {
attribute(previous, options, details) {
if (details.attributeName === "full_name") {
return "name";
} else {
return previous?.(details) ?? details.attributeName;
}
},
},
},
};

Writing Plugins编写插件​

We’ve created a number of plugin helpers for common tasks:

针对常见需求,我们提供了一系列插件辅助工具:

For everything else, you can write raw Graphile Build plugins.

其余所有高级需求,都可以直接编写原生 Graphile Build 插件来实现。

Do look over our plugin gallery for examples of plugins. These are generally suitable for copying/pasting into your app and then customizing to your needs.

也建议浏览我们的插件画廊,里面收录了不少实用插件示例。这些代码通常可以直接复制粘贴到你的项目中,再按实际需求微调。

Loading Plugins加载插件​

Once you’ve written (or installed) a plugin, you can load it via your preset:

编写(或安装)好插件后,即可通过 preset 加载它:

graphile.config.mjs
import MyPlugin from "./myPlugin.mjs";

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

Remember: multiple versions of graphql in your node_modules will cause problems; so we strongly recommend using the graphql object that's available on the Build object (second argument to hooks) rather than requiring your own version.

请注意:如果 node_modules 中存在多个版本的 graphql,将会引发兼容问题;因此我们强烈建议直接复用 Build 对象(hook 函数的第二个参数)上挂载的 graphql 对象,而不要自行引入其他版本。

Schema pluginsSchema 插件​