Skip to main content

Migrating Custom Plugins迁移自定义插件

If you've written some PostGraphile V4 plugins by hand (not using one of the make...Plugin helpers) then this migration guide is for you. We'll step you through some of the key changes.

如果你曾手动编写过 PostGraphile V4 插件(未使用各类 make...Plugin 辅助函数),本迁移指南正是为你准备的。下面我们将带你逐一了解其中的关键变更。

Overview概览​

Here's the rough process:

大致迁移步骤如下:

  1. Ensure you have tests and that they pass

    确保已有测试套件且测试全部通过

  2. Move all require() calls to the top (not inside of functions)

    将所有 require() 调用移至文件顶部(不要写在函数内部)

  3. Convert your tests to TypeScript (or use // @ts-check) and fix errors

    将测试也迁移为 TypeScript(或使用 // @ts-check),并修复报错

  4. Ensure your tests still pass

    确认测试依然全部通过

  5. Ensure your tests still pass

    确认测试依然全部通过

Convert the plugin to TypeScript将插件迁移为 TypeScript​

(You can read why converting to TypeScript is so important in the TypeScript section below.)

(关于为何迁移到 TypeScript 如此重要,可参阅下文的 TypeScript 支持章节。)

We recommend that you extend from the @tsconfig/node22 preset; you can disable noImplicitAny to massively reduce the number of TypeScript errors you need to deal with:

建议继承 @tsconfig/node22 preset;在此期间可以先关闭 noImplicitAny,以大幅减少需要处理的 TypeScript 报错数量:

tsconfig.json
{
"extends": "@tsconfig/node22/tsconfig.json",
"compilerOptions": {
// You may want to enable this flag in V4 since V4 types were extremely
// loose (since it was originally written in Flow, not TypeScript):
//
// "noImplicitAny": false,

// If your tests are written in JS you'll need this for subpath importing
// to work:
"allowJs": true,

"rootDir": "./src",
"outDir": "./dist",
"declarationDir": "dist",
"declaration": true,
"sourceMap": true
},
"exclude": ["node_modules"]
}
It's okay to make this TypeScript config loose for V4V4 阶段可以把 TypeScript 配置放宽一些

The main thing is to make it so we're using TypeScript syntax, that TypeScript compiles, and that our tests run the compiled code. Once we've ported to V5 we'll make the types a lot stricter.

这一步的关键在于先用上 TypeScript 语法、让 TypeScript 顺利编译通过,并确保测试运行的是编译后的代码。等迁移到 V5 之后,我们再把类型检查收紧。

Don't forget to update your package.json to point to the new locations and add a prepack script to compile your TypeScript:

别忘了更新 package.json,使其指向编译后的新路径,并添加 prepack 脚本来编译 TypeScript 代码:

package.json
{
// ...
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": ["dist"],
"scripts": {
// ...
"watch": "tsc --watch",
"prepack": "tsc"
},
"devDependencies": {
// ...
"@tsconfig/node22": "^22.0.5",
"typescript": "^5.7.2"
}
}

Upgrade to V5 dependencies升级至 V5 依赖​

Go through each PostGraphile V4 related package referenced in package.json and install the latest version of it, for example:

逐一排查 package.json 中引用的所有 PostGraphile V4 相关包,并安装其最新版本,例如:

package.json before
{
"devDependencies": {
"graphile-build": "^4.12.0-alpha.0",
"graphile-build-pg": "^4.12.0-alpha.0",
"postgraphile": "^4.12.0-alpha.0",
"postgraphile-plugin-connection-filter": "^2.2.0"
}
}
yarn add --dev \
graphile-build \
graphile-build-pg \
postgraphile \
postgraphile-plugin-connection-filter
package.json after
{
"devDependencies": {
"graphile-build": "^5.0.0-rc.3",
"graphile-build-pg": "^5.0.0-rc.3",
"postgraphile": "^5.0.0-rc.4",
"postgraphile-plugin-connection-filter": "^3.0.0-rc.1"
}
}
postgraphile-core is no morepostgraphile-core 已成为历史

Huh... that rhymed. But yeah, just use postgraphile instead.

呃……这句在英文里居然还押韵。不过确实,现在直接改用 postgraphile 就行。

Use subpaths instead of explicit modules where possible尽量通过子路径导入,避免直接声明显式子模块依赖

It's really annoying when you end up with version conflicts, so in V5 we've made it easy for you to consistently install one version of the package and depend on parts within that; instead of import { ... } from "graphile-build" you would now do import { ... } from "postgraphile/graphile-build" — that way you don't need to list graphile-build as a dependency. Your package.json can now be just:

依赖版本冲突向来让人头疼,因此 V5 让你只需统一安装一个主包,再按需从中引入各个组成部分即可。比如原先的 import { ... } from "graphile-build" 现在可以改写为 import { ... } from "postgraphile/graphile-build"——这样就不再需要将 graphile-build 单独列为依赖了。此时你的 package.json 可以精简为:

package.json using subpaths for graphile-build*
{
"devDependencies": {
"postgraphile": "^5.0.0-rc.4",
"postgraphile-plugin-connection-filter": "^3.0.0-rc.1"
}
}

You should do this for graphql as well: import { ... } from "postgraphile/graphql".

对于 graphql 也建议采用同样的方式:import { ... } from "postgraphile/graphql"。

Perform basic code transforms执行基础代码转换​

TODO: write some codemods to help with this.

TODO:后续会补充一些 codemod 工具来辅助完成这一步。

See Plugins below for full details, but essentially a V4 plugin like:

完整细节请参阅下文的 Plugins(插件) 一节。简而言之,像下面这样的 V4 插件:

v4.ts
import { Plugin } from "graphile-build";

export const MyPlugin: Plugin = (builder) => {
builder.hook("inflection", (inflection, build) => {
return build.extend(inflection, {
myInflector(stuff) {
return stuff + "Stuff";
},
});
});

builder.hook("build", (build) => {
return build.extend(
build,
{ myStuff: () => ["my", "stuff"] },
"Adding myStuff to build",
);
});

builder.hook("init", (_, build) => {
doSomethingWith(build.myStuff());
return _;
});

builder.hook("GraphQLObjectType:fields", (fields, build, context) => {
return build.extend(
fields,
{ myField: { type: build.graphql.GraphQLString } },
"Adding fields from MyPlugin",
);
});
};

in V5 would become a declarative structured object rather than a function containing a lot of function calls:

到了 V5 会变为一个声明式的结构化对象,而不再是包含大量函数调用的函数:

v5.ts
import type {} from "postgraphile";

export const MyPlugin: GraphileConfig.Plugin = {
name: "MyPlugin",

inflection: {
add: {
myInflector(stuff) {
return stuff + "Stuff";
},
},
},

schema: {
hooks: {
build(build) {
return build.extend(
build,
{ myStuff: () => ["my", "stuff"] },
"Adding myStuff to build",
);
},

init(_, build) {
doSomethingWith(build.myStuff());
return _;
},

GraphQLObjectType_fields(fields, build, context) {
return build.extend(
fields,
{ myField: { type: build.graphql.GraphQLString } },
"Adding fields from MyPlugin",
);
},
},
},
};

Turn on strict typing开启严格类型检查​

Importantly you need at least the following:

最重要的是,你至少需要启用以下配置项:

tsconfig.json
{
"compilerOptions": {
// ...
"strict": true,
"noImplicitAny": true
}
}

Fix the TypeScript errors修复 TypeScript 错误​

Run yarn tsc --watch or similar in a terminal, and start working through the errors top to bottom. For each error, find the relevant part of this guide and follow the advice. If it's not clear, ask on Discord and then submit an update to this page with details - thanks for contributing to making everyone's migration to V5 easier!

在终端中运行 yarn tsc --watch 或类似命令,然后从上到下逐个解决报错。针对每条错误,在本指南中找到对应章节按建议处理即可。如果遇到不清楚的地方,欢迎前往 Discord 提问,并在解决后提交更新,将细节补充到本页面中——感谢你的贡献,让所有人向 V5 的迁移变得更轻松!

Make your plugin exportable使插件支持导出​

This is optional, you only need it if you want people to be able to use Graphile Export to export a schema using this plugin as executable code, for example to use in serverless situations where boot-up time is at a premium.

这一步是可选的,仅当你希望用户能够通过 Graphile Export 将使用了该插件的 schema 导出为可执行代码时才需要(例如在启动耗时极其关键的 Serverless 场景中)。

TODO:此处待补充完整文档!目前请先参阅:导出你的 schema 以及 https://star.graphile.org/graphile-export/

TypeScriptTypeScript 支持​

It is very strongly recommended that you write plugins in TypeScript. There are two main reasons for this:

非常强烈建议使用 TypeScript 编写插件,主要原因有两点:

  1. A lot of work has gone into making the plugin and configuration system strongly typed so that you gain auto-complete and documentation on every option, this should make your plugin authoring experience much easier than in V4.

    我们在插件和配置系统的强类型支持上投入了大量精力,使每个选项都具备自动补全和文档提示,这会让插件开发体验比 V4 顺畅得多。

  2. Since the plugin and configuration system is strongly typed, if you do not extend these types when you're writing your plugin, users that use TypeScript will not be able to supply your configuration options easily.

    正因插件与配置系统是强类型的,如果编写插件时不扩展对应类型,使用 TypeScript 的用户就无法方便地传入你的插件配置项。

Since your plugin will likely add attributes to various shared object types, we use declaration merging heavily. Declaration merging allows you to add additional attributes to existing TypeScript interfaces. You should familiarize yourself with declaration merging in the TypeScript documentation if you are not already familiar.

由于插件很可能需要向各种共享对象类型添加属性,V5 大量使用了声明合并(Declaration Merging)机制,用以向现有的 TypeScript 接口追加新属性。如果你还不熟悉这一特性,建议先阅读 TypeScript 官方文档中的声明合并章节。

To avoid problems that come from having multiple versions of the same module thanks to the many and varied package managers (and versions thereof) all having their own ideas about which modules should be installed where, we merge into globally scoped namespaces. The main roots for these namespaces that you'll work with are GraphileConfig and GraphileBuild.

由于各类包管理器及其不同版本对模块的安装位置各有主见,很容易导致同一模块出现多份副本并引发类型冲突。为规避这一问题,我们统一合并到全局作用域的命名空间(namespace)中,日常开发主要会用到 GraphileConfig 和 GraphileBuild 这两个根命名空间。

Many of the types need to be converted, here's a few:

许多类型都需要相应迁移,以下列举其中几项:

  • import("graphile-build").Build -> GraphileBuild.Build
  • import("graphile-build").Inflection -> GraphileBuild.Inflection
  • import("graphile-build").Plugin -> GraphileConfig.Plugin (the inflection, gather and schema scopes therein)

    import("graphile-build").Plugin -> GraphileConfig.Plugin(对应其中的 inflection、gather 与 schema 作用域)

  • import("postgraphile").PostGraphilePlugin -> GraphileConfig.Plugin (the grafast and grafserv scopes therein)

    import("postgraphile").PostGraphilePlugin -> GraphileConfig.Plugin(对应其中的 grafast 与 grafserv 作用域)

  • import("postgraphile").PostGraphileOptions -> GraphileConfig.Preset (split across the various scopes therein)

    import("postgraphile").PostGraphileOptions -> GraphileConfig.Preset(分散在其中的各个作用域内)

General migration changes通用迁移变更​

Your test suite likely uses standard APIs, so will need to follow the regular V4 migration guide.

你的测试套件通常会用到标准 API,因此也需要遵循常规的 V4 迁移指南。

No look-ahead移除 look-ahead 机制​

Graphile Build no longer has a look-ahead engine, instead it uses Grafast plans. (You should familiarize yourself with Grafast's documentation.)

Graphile Build 不再内置 look-ahead 引擎,而是改用 Grafast 执行计划。(建议先熟悉一下 Grafast 文档。)

That means all of the APIs that related to "data generators" and the QueryBuilder and similar no longer exist:

这意味着所有与“data generators(数据生成器)”以及 QueryBuilder 等相关的 API 均已不复存在:

  • 🚮 QueryBuilder
  • 🚮 getDataFromParsedResolveInfoFragment
  • 🚮 addDataGenerator
  • 🚮 addArgDataGenerator
  • 🚮 queryFromResolveData
  • 🚮 selectGraphQLResultFromTable

Similarly you should no longer use resolvers since Grafast plan resolvers replace both of these needs. (You can use traditional resolvers with Grafast, but they lose many of the benefits of plan resolvers. Further, a Grafast plan that does not use any traditional resolvers is considered "pure", so your plugin should aim to not "taint" your users' schemas.)

同样,你也不应再编写传统 resolver,因为 Grafast 的 plan resolver 已同时取代了上述两类需求。(虽然在 Grafast 中你 依然可以 使用传统 resolver,但那样会失去 plan resolver 的诸多优势。此外,完全不使用传统 resolver 的 Grafast 执行计划被视为“纯净(pure)”计划,因此你的插件也应尽量避免“污染”用户的 schema。)

The good news is that Grafast plan resolvers are typically much (much) shorter and easier to read, write and understand compared to the chaotic mess that was V4's look-ahead system. We'll look at this a bit more in Plans below.

好消息是,相比 V4 中错综复杂的 look-ahead 系统,Grafast 的 plan resolver 通常要精简得多(而且不是一点点),写起来、读起来和理解起来都容易得多。下文的 Plans(执行计划) 一节会进一步介绍相关内容。

Type registration类型注册​

In V4 you could define types in an ad-hoc manner as and when you needed them using the newWithHooks() function, but this caused havoc at runtime because it meant that sometimes a type didn't already exist when you needed it — they were very dependent on ordering. This was particularly obvious when using makeExtendSchemaPlugin and trying to use auto-generated types that may or may not exist yet. Worse still, plugins that built types only if a type with that name didn't already exist could get tricked into using an incompatible type!

在 V4 中,你可以随时随地通过 newWithHooks() 临时定义类型,但这在运行时常常引发混乱:由于高度依赖执行顺序,某些时候你要用的类型可能尚未创建。在使用 makeExtendSchemaPlugin 并尝试引用可能尚未生成的自动类型时,这个问题尤为突出。更糟糕的是,有些插件会采用“仅当同名类型不存在时才创建”的逻辑,结果反而可能误用上不兼容的类型!

In V5, all types must be registered by name during the init hook. The types still are not created until they are needed (and may not be created at all), but their names and spec generation functions must be registered ahead of time. This means that when building fields and arguments you can always reference a type by its name (using build.getTypeByName('TypeNameHere')).

在 V5 中,所有类型都必须在 init hook 阶段按名称提前注册。虽然具体类型依然会在真正被用到时才实例化(甚至可能根本不会被创建),但其名称以及用于生成规格对象的回调函数必须事先注册好。这样一来,在构建字段和参数时,你随时可以通过名称引用任意类型(使用 build.getTypeByName('TypeNameHere'))。

Instead of build.newWithHooks you should use the registration methods (note that instead of passing the constructor as you did in build.newWithHooks, you choose the correctly named function):

请改用以下类型注册方法来替代 build.newWithHooks(注意:不再像 build.newWithHooks 那样传入构造函数,而是直接选用名称对应的注册函数):

  • build.registerObjectType(typeName, scope, specCallback, origin)
  • build.registerInterfaceType(typeName, scope, specCallback, origin)
  • build.registerUnionType(typeName, scope, specCallback, origin)
  • build.registerScalarType(typeName, scope, specCallback, origin)
  • build.registerEnumType(typeName, scope, specCallback, origin)
  • build.registerInputObjectType(typeName, scope, specCallback, origin)

They each take 4 arguments:

这些方法均接收 4 个参数:

  • typeName is the (unique) name of the type (this would typically come from an inflector)

    typeName:类型的唯一名称(通常由 inflector 生成)

  • scope is an object with any GraphileBuild.Scope data relevant to this hook, useful for other plugins to register hooks against the type

    scope:一个包含与该 hook 相关的 GraphileBuild.Scope 数据的对象,方便其他插件针对该类型挂载 hook

  • specCallback is a callback function that takes no arguments and returns the spec object. Spec objects are similar to the ones that would be used with GraphQL.js constructors, except they have an extra couple of optional convenience properties specific to Grafast.

    specCallback:不接收参数并返回 spec 对象的回调函数。spec 对象与传给 GraphQL.js 构造函数的配置对象类似,只是额外提供了几个 Grafast 专属的可选便捷属性。

  • origin is a string describing where this type came from / why it exists - it's particularly handy when two types try and register the same name

    origin:一段描述该类型来源或用途的字符串,当两个类型意外注册了相同名称时,这个信息尤其有助于排查冲突

Example示例​

const MyPlugin: GraphileConfig.Plugin = {
name: "MyPlugin",
version: "0.0.0",

schema: {
hooks: {
init(_, build) {
const typeName = inflection.myInflector("MyInflectorInput");

build.registerObjectType(
typeName,
{
/* add scope data here */
},
() => ({
// Here's the spec for the type
description: "...",
fields: {
//...
},

// If this type requires a particular step class, optionally
// specify it here:
//
// assertStep: ObjectStep,
//
// Or if you prefer, you can make `assertStep` a callback that
// throws an error if the step passed is incompatible:
//
// assertStep($step: Step): asserts $step is ObjectStep {
// if (!($step instanceof ObjectStep)) {
// throw new Error(`Expected ObjectStep, instead received '${$step}'`);
// }
// },
}),
`Here you'd put a helpful phrase detailing why this type is being registered; useful when two types try and register with the same name`,
);

return _;
},
},
},
};

IntrospectionIntrospection(内省)​

In V5 we've split the schema build process into two parts:

在 V5 中,我们将 schema 的构建流程拆分为两个阶段:

  • gather is where data is gathered from external sources (databases, APIs, the file system, etc) and converted into an "input" to feed into the schema phase. Critically, gather is asynchronous.

    gather:负责从外部数据源(数据库、API、文件系统等)采集信息,并将其转换为供 schema 阶段使用的“输入(input)”。关键在于,gather 阶段是异步执行的。

  • schema is where the GraphQL schema is produced from the gathered "input". Critically, schema is synchronous.

    schema:负责基于采集到的“输入(input)”构建出最终的 GraphQL schema。关键在于,schema 阶段是同步执行的。

Introspection data is only available in the gather phase, from there it's converted into abstractions (resources, codecs, relations and behaviors) which are used during the schema phase. Further the introspection system has been replaced by a standalone module pg-introspection which is strongly typed — it actually embeds parts of the TypeScript documentation so that when you hover over its various properties in your editor it will tell you how Postgres describes those fields!

introspection 数据仅在 gather 阶段可用,随后会被转换为各类抽象对象(包括 resource、codec、relation 和 behavior),供 schema 阶段使用。此外,原有的 introspection 系统已被替换为强类型的独立模块 pg-introspection——该模块中甚至直接内嵌了部分文档注释,当你在编辑器中将鼠标悬停在各属性上时,就能直接看到 Postgres 对相应字段的官方说明!

As such pgIntrospectionResultsByKind is no more, and anything that you had that relied on introspection results will need to be mapped to using the abstractions. Typically this results in your code being a bit simpler, but there are somethings you should pay particular attention to:

因此,pgIntrospectionResultsByKind 已被彻底移除,过去依赖 introspection 结果的逻辑都需要改写为使用这些抽象对象。通常这会让你的代码更简洁,但有几处细节需要特别留意:

  • In V4 you'd often look at the foreign key constraints on a table and go "forwards" and "backwards" from them. In V5 the abstraction for these is a relation, which only represents one direction. A "backwards" relation is one that has the "isReferencee" property set. The backward and forward relations can have different smart tags.

    在 V4 中,你常常会查看表上的外键约束,并沿着它进行“正向”和“反向”关联遍历。在 V5 中,外键约束被抽象为 relation,而每个 relation 仅代表单向关系;“反向” relation 即带有 "isReferencee" 属性的 relation。正向和反向 relation 可以拥有不同的 smart tag。

  • Whereas in V4 you'd think in terms of "classes" (tables, views, etc) and "procs" (functions), in V5 these are all abstracted as "resources" (functions are resources that accept parameters, table-likes are resources that don't); and importantly every resource has a codec that describes what it returns. Sometimes you should focus on codec (e.g. when it doesn't matter if the row has come from a table or function) whereas others you should focus on the resource (when you need to actually get the row).

    在 V4 中,你往往需要区分“classes”(表、视图等)和“procs”(函数);而在 V5 中,它们被统一抽象为“resource”(函数是接收 parameters 的 resource,而类表对象则是不接收参数的 resource)。更重要的是,每个 resource 都关联着一个描述其返回结构的 codec。有些场景下你应该关注 codec(例如不在乎数据行究竟来自表还是函数时),而在另一些场景下则需要关注 resource 本身(当你需要真正去 获取 数据行时)。

  • Changes to behaviors (@omit/etc) should be done during the gather phase if they require fetching additional data (e.g. from files, databases, APIs, etc), or using the behavior system otherwise.

    如果需要调整 behavior(例如 @omit 等),当调整逻辑依赖额外的数据获取操作(例如读取文件、查询数据库、调用 API 等)时,应在 gather 阶段完成;否则直接使用 behavior 系统即可。

PresetsPreset(预设)​

Presets are a collection of plugins, configuration options, and other presets that get merged together recursively to build the users ultimate configuration. A preset is an object with the following base properties (all optional):

preset 是由插件、配置选项以及其他 preset 组成的集合,它们会被递归合并,最终构建出用户的完整配置。preset 对象包含以下基础属性(均为可选):

  • extends - a list of presets that this preset extends

    extends —— 当前 preset 所继承的其他 preset 列表

  • plugins - a list of plugin objects that this preset makes use of

    plugins —— 当前 preset 所使用的插件对象列表

  • disablePlugins - a list of plugin names (strings) that should be disabled (skipped)

    disablePlugins —— 需要禁用(跳过)的插件 名称(字符串)列表

In addition to these common properties, Graphile Config presets have additional optional fields to influence various different "scopes". For more details, see configuration.

除了上述通用属性外,Graphile Config preset 还提供其他可选字段,用于控制各个不同的“作用域(scope)”。详情请参阅配置文档。

In V4 we had a plugin helper called makePluginByCombiningPlugins; in V5 that's better served by using a preset that simply lists the underlying plugins to be combined.

在 V4 中我们曾提供过 makePluginByCombiningPlugins 辅助函数;而在 V5 中,更好的做法是直接定义一个 preset,在其中列出需要组合的底层插件即可。

info说明

Critically, a preset must not have a name property; this property helps to distinguish between presets and plugins.

切记:preset 绝对不能包含 name 属性,系统正是通过该属性来区分 preset 与插件的。

PluginsPlugins(插件)​

In PostGraphile V4 there were two types of plugins:

在 PostGraphile V4 中,插件分为两类:

  • schema plugins (functions) interacted with Graphile Engine (graphile-build and graphile-build-pg) and were responsible to changes to your GraphQL schema

    schema 插件(函数形式):与 Graphile Engine(graphile-build 和 graphile-build-pg)交互,负责定制 GraphQL schema

  • server plugins (objects) interacted with PostGraphile and it's server/CLI and were responsible to changes to how the HTTP requests were handled and other "high level" concerns (including such concerns as which additional schema plugins to load!)

    服务端插件(对象形式):与 PostGraphile 及其服务端/CLI 交互,负责调整 HTTP 请求的处理方式以及其他“高层级”事务(例如指定需要额外加载哪些 schema 插件!)

In V5 there is only one type of plugin, a Graphile Config plugin. Graphile Config plugins are objects with the following properties:

在 V5 中,插件已统一为一种形式,即 Graphile Config 插件。Graphile Config 插件是一个包含以下属性的对象:

  • name (required) - a unique name for this plugin

    name(必填)—— 该插件的唯一名称

  • version (required) a semver-formatted version string

    version(必填)—— 符合 semver 规范的版本号字符串

  • description - a short description of the plugin for use in documentation

    description —— 插件的简短描述,用于文档展示

  • experimental - set this true if the plugin is experimental (no current effect)

    experimental —— 若插件仍处于实验阶段则设为 true(目前暂无实际效果)

  • provides - a list of "features" (arbitrary strings) that the plugin provides; the plugin name is automatically included in this list

    provides —— 该插件所提供的“特性(feature)”(任意字符串)列表;插件自身的 name 会自动包含在此列表中

  • after - a list of "features" that need to be established before this plugin runs

    after —— 必须在本插件运行之前就绪的“特性”列表

  • before - a list of "features" that must not be processed until after this plugin runs

    before —— 必须在本插件运行之后才能处理的“特性”列表

In addition to these common properties, Graphile Config plugins have additional optional fields to influence various different "scopes".

除了上述通用属性外,Graphile Config 插件还提供其他可选字段,用于介入各个不同的“作用域(scope)”。

V4 "schema" plugins are now primarily concerned with these scopes:

原来的 V4“schema”插件现在主要涉及以下作用域:

  • inflection - naming things

    inflection —— 控制各类命名规则

  • gather - gathering the data necessary to build the schema, and outputting a registry

    gather —— 采集构建 schema 所需的数据,并输出 registry

  • schema - assigning behaviors to entries in the registry and then building a GraphQL schema based on these

    schema —— 为 registry 中的条目分配 behavior,并据此构建出 GraphQL schema

Server plugins are likely more concerned with these scopes:

原来的服务端插件则更可能涉及以下作用域:

  • grafserv - handing HTTP requests

    grafserv —— 处理 HTTP 请求

  • grafast - handling the GraphQL request (e.g. manipulating the context, etc)

    grafast —— 处理 GraphQL 请求(例如修改上下文 context 等)

info说明

Currently the postgraphile CLI does not accept many options — it is intended that users will provide options via the graphile.config.ts (or similar) file — so there is no plugin interface for adding CLI flags.

目前 postgraphile CLI 本身只接受极少数命令行参数——设计初衷是让用户通过 graphile.config.ts(或同类配置文件)传入选项——因此插件暂不提供用于扩展 CLI 参数的接口。

plugin.inflectionplugin.inflection(命名推导)​

In V4, "inflection" was one of the hooks that were called whilst building a schema. In V5, inflection has been promoted to its own phase, primarily because "naming things" is a global concern that applies to both the gather and schema phases (see below). Inflectors are also now defined in a declarative (i.e. object properties) way, rather than an imperative (i.e. function calls) way — this allows the system to inspect plugins without executing them.

在 V4 中,“inflection”只是构建 schema 时调用的众多 hook 之一。而在 V5 中,命名推导 inflection 已升级为独立的阶段,主要因为“命名”是一项全局职责,会同时作用于 gather 和 schema 两个阶段(见下文)。此外,inflector 的定义方式也从命令式(函数调用)改为了声明式(对象属性),从而让系统无需执行插件代码即可检视插件内容。

.add.add(新增 inflector)​

Used to add inflectors; when doing so you should also add their type definitions. Note that the type definitions only include the arguments that you call the inflector with, the inflector implementation has an extra initial argument (options) that the system automatically passes.

用于新增 inflector;添加时应同步补充对应的类型定义。注意,类型定义中只需包含调用该 inflector 时实际传入的参数,而 inflector 的具体实现函数在最前面会多出一个由系统自动传入的 options 参数。

Defining connection and list fields should now use the this.listField(...) and this.connectionField(...) inflectors respectively as part of their implementation, this will ensure that the fields are consistently named across the schema.

定义列表字段和 Connection 字段时,现在应分别在实现中调用 this.listField(...) 和 this.connectionField(...) inflector,以确保整个 schema 中的字段命名风格保持一致。

The inflectors available have changed a little, use the TypeScript auto-completion to see what inflectors are available.

可用的内置 inflector 相比 V4 略有变化,你可以直接借助 TypeScript 的自动补全来查看当前有哪些 inflector 可用。

Example示例​
// Declare the type
declare global {
namespace GraphileBuild {
interface Inflection {
/** Field name for a Connection field returning all rows from the resource. */
allRowsConnection(this: Inflection, resource: PgResource): string;
}
}
}

// Implement the inflector
export const PgAllRowsPlugin: GraphileConfig.Plugin = {
name: "PgAllRowsPlugin",
version: "0.0.0",

inflection: {
add: {
allRowsConnection(
options, // Additional argument, automatically passed by the system
resource, // This is the argument you defined in the types above
) {
return this.connectionField(
this.camelCase(
`all-${this.pluralize(this._singularizedResourceName(resource))}`,
),
);
},
// ...
},
},
// ...
};

.replace.replace(替换 inflector)​

Should you wish to replace an inflector, you may use this hook instead. It works similarly to add above, with the following two differences:

如果你想替换已有的 inflector,可以使用此 hook。它的用法与上文的 add 类似,仅有以下两点区别:

  1. The type declaration is not required (since it already exists, right?)

    无需编写类型声明(毕竟原有类型定义已经存在了,对吧?)

  2. an additional first argument is prepended onto the arguments list: prev; this is the previous implementation of the inflector, for your inflector to call should it need to.

    参数列表的最前面会额外多出一个首参 prev,它指向该 inflector 之前的实现,方便你在新实现中按需调用。

.ignoreReplaceIfNotExists.ignoreReplaceIfNotExists(目标不存在时忽略替换)​

You can "replace" an inflector that doesn't exist, but a) you'll get a warning, and b) the prev function will be null or undefined.

你确实可以“替换”一个尚不存在的 inflector,但这样会导致两个后果:a)系统会发出警告;b)prev 参数的值将为 null 或 undefined。

Alternatively, include the name of the inflector in ignoreReplaceIfNotExists (array of strings), and if the inflector didn't previously exist then it will continue to not exist (and we won't warn you about it). This also means that the prev argument is guaranteed to exist at runtime.

另一种做法是将该 inflector 的名称加入 ignoreReplaceIfNotExists(字符串数组)中。这样一来,如果此前不存在该 inflector,系统会跳过替换让它继续保持不存在(同时也不会发出警告);这也意味着在运行时 prev 参数必然存在。

Example示例​
export const PgAllThePeoplePlugin: GraphileConfig.Plugin = {
name: "PgAllThePeoplePlugin",
version: "0.0.0",

inflection: {
replace: {
allRowsConnection(prev, options, resource) {
return resource.name === "people" ? `allThePeople` : prev!(resource);
},
ignoreReplaceIfNotExists: ["allRowsConnection"],
},
},
};

plugin.gatherplugin.gather(数据采集)​

If your plugin did anything asynchronous (extremely unlikely) then that work would now be done during the gather phase. If this is the case, please reach out to Benjie for additional documentation!

如果你的插件过去执行过任何异步操作(这种情况极少见),现在这些工作都应放到 gather 阶段中完成。若确有此类需求,欢迎联系 Benjie 获取进一步文档指导!

plugin.schemaplugin.schema(构建 schema)​

Configures the behavior system and implements the schema hooks

用于配置 behavior 系统并实现各类 schema hook

.globalBehavior and .entityBehavior.globalBehavior 与 .entityBehavior​

The '@omit' and '@simpleCollections' smart tags have been replaced with the behavior system in V5. Though the V4 preset adds compatibility with the V4 @omit system (by converting the @omit tags to behaviors), your plugins should not use the data from @omit — they should use the behavior data exclusively.

在 V5 中,原有的 '@omit' 和 '@simpleCollections' smart tag 已被 behavior 系统取代。尽管 V4 兼容 preset 通过将 @omit 标签转换为 behavior 的方式保留了向后兼容,但你的插件 不应 再读取 @omit 的原始数据——而应一律使用 behavior 数据。

For more information on behavior, see Behavior.

有关 behavior 的更多信息,请参阅 Behavior。

.hooks.hooks(schema 钩子)​

If you were writing a schema plugin, this is where the bulk of your replacement will go.

如果你之前编写的是 schema 插件,那么绝大部分迁移改动都会落在这里。

This is where your schema hooks get registered now. A simple first change is that we've moved from a procedural style to a declarative style. Further, we've replaced all the : in the hook names with _ to avoid needing quote marks and to make them easier to copy/paste (since it's more likely that word selection in an editor will select the whole string). The three arguments are still essentially the same as they were.

现在所有的 schema hook 都在此处注册。第一个显而易见的变化是从过程式写法改为了声明式写法;此外,我们还将 hook 名称中的所有 : 替换成了 _,这样不仅省去了引号,也更便于复制粘贴(在编辑器中双击选词时能直接选中整个名称)。hook 回调接收的三个参数基本上与原先保持一致。

For example, a V4 plugin that looks like:

例如,一个如下所示的 V4 插件:

const ExamplePlugin: Plugin = (builder) => {
builder.hook("GraphQLObjectType:fields", (fields, build, context) => {
// ...
return fields;
});
};

would look like this in V5:

在 V5 中会改写为:

const ExamplePlugin: GraphileConfig.Plugin = {
name: "ExamplePlugin",
version: "0.0.0",

schema: {
hooks: {
GraphQLObjectType_fields(fields, build, context) {
//...
return fields;
},
},
},
};

Extending build扩展 build 对象​

If your plugin adds capabilities to GraphileBuild.Build then it must register them with TypeScript via declaration merging. For example to add a flibble property to GraphileBuild.Build, you might do:

如果你的插件向 GraphileBuild.Build 添加了新能力,就必须通过声明合并向 TypeScript 注册对应的类型。例如,若要向 GraphileBuild.Build 添加一个 flibble 属性,可以这样写:

// Ensure that the types are imported for TypeScript
import "postgraphile";

// Extend the global GraphileBuild.Build type to add our 'flibble' attribute:
declare global {
namespace GraphileBuild {
interface Build {
flibble: bool;
}
}
}

// And here's the plugin that actually adds the attribute at runtime:
export const FlibblePlugin: GraphileConfig.Plugin = {
name: "FlibblePlugin",
version: "0.0.0",
schema: {
hooks: {
build(build) {
build.flibble = true;
return build;
},
},
},
};

Extending scopes扩展 scope 类型​

Similarly all of the scopes and contexts are typed within each hook by camelCasing the hook name and prepending Scope or Context. For example, the scope in the GraphQLObjectType_fields_field hook is now ScopeObjectFieldsField. If you need to add additional entries to any of these you should do so via declaration merging, and you should ensure that the property is optional:

同理,每个 hook 对应的 scope 和 context 都有专门的类型定义,其命名规则是将 hook 名称转为驼峰形式,并在前面加上 Scope 或 Context。例如,GraphQLObjectType_fields_field hook 中的 scope 类型现在名为 ScopeObjectFieldsField。如果需要向其中添加额外字段,应通过声明合并来完成,并且务必确保新增属性是可选的:

declare global {
namespace GraphileBuild {
interface ScopeObjectFieldsField {
isRootNodeField?: boolean;
}
}
}

Adding configuration options添加配置选项​

If your plugin requires the user to pass configuration options, most likely they should be in the preset.schema scope which should be retrieved via build.options. When doing so, we also need to add to the declaration-merged types so that TypeScript understands the presence of the new option:

如果你的插件需要由用户传入配置选项,这些选项通常应放在 preset.schema 作用域下,并在代码中通过 build.options 读取。与此同时,我们还需要通过声明合并扩展相应类型,以便 TypeScript 能够识别新增的配置项:

declare global {
namespace GraphileBuild {
interface SchemaOptions {
/**
* The default option to use for the 'includeArchived' argument. Defaults to
* 'INHERIT' where feasible and 'NO' otherwise.
*/
pgArchivedDefault?: "INHERIT" | "NO" | "YES" | "EXCLUSIVELY";
}
}
}

Note also that tools like graphile config options will look at these TypeScript definitions and use them to provide documentation to the user — as such you should be sure to add a /** ... */ comment describing the feature, as we have above.

另外请注意,graphile config options 等工具会直接读取这些 TypeScript 类型定义,并以此向用户生成配置说明文档——因此请务必像上面示例那样,为配置项写上 /** ... */ 文档注释。

PlansPlans(执行计划)​

As we read earlier, there's no look-ahead system in PostGraphile V5; instead we use Grafast's planning system.

正如前文所述,PostGraphile V5 中已不再有 look-ahead 系统,取而代之的是 Grafast 的执行计划体系。

Where you used to use addArgDataGenerator you should now give your argument an applyPlan.

过去使用 addArgDataGenerator 的地方,现在应当为该参数定义一个 applyPlan。

Typically where you'd use a QueryBuilder (queryBuilder) in V4, you'll be dealing with a PgSelectStep ($pgSelect) in V5. Note that these are significantly different things, but they do have some parallels:

通常情况下,V4 中使用 QueryBuilder(queryBuilder)的场景,在 V5 中对应的都是 PgSelectStep($pgSelect)。虽然两者在设计上有本质差异,但仍存在一些可类比的用法:

  • QueryBuilder.getTableAlias() -> $pgSelect.alias
  • QueryBuilder.where(...) -> $pgSelect.where((sql) => ...)
  • QueryBuilder.orderBy(...) -> $pgSelect.orderBy((sql) => ...) (arguments differ, see TypeScript for details)

    QueryBuilder.orderBy(...) -> $pgSelect.orderBy((sql) => ...)(参数有所差异,具体请参考 TypeScript 类型定义)

Note that it's common to be dealing with a PgSelectSingleStep ($pgSelectSingle) when you're looking at a single record rather than the collection. In this case should you need to get back to the collection (e.g. to get the alias) you can do $pgSelectSingle.getClassStep().

注意,当处理的是单条记录而非集合时,你拿到的通常是 PgSelectSingleStep($pgSelectSingle)。此时若需要回溯到所属的集合 step(例如为了获取表别名),可以调用 $pgSelectSingle.getClassStep()。

Should you have code that uses queryBuilder.parentQueryBuilder there's no direct parallel. Instead, you should use the parent step and get what you need from there, and then embed that value into your query:

如果原有代码中用到了 queryBuilder.parentQueryBuilder,V5 中并没有直接对应的属性。正确做法是从父级 step 中提取所需数据,再将该值嵌入到当前查询中:

// V4
const parentAlias = queryBuilder.parentQueryBuilder.getTableAlias();
queryBuilder.where(sql.fragment`${parentAlias}.archived_at is not null`);

// V5
const $archivedAt = $parent.get("archived_at");
$pgSelect.where((sql) => sql`${$archivedAt} is not null`);
info说明

applyPlan on an argument accepts 4 arguments, the first is the parent step ($parent), which is the step that the field itself was called on. The second is the target step ($pgSelect), which is typically the result of the fields' plan resolver. Note that input objects' applyPlans only have the latter 3 arguments — they do not have access to the parent step unless their parent input object or argument applyPlan explicitly pass them down.

字段参数上的 applyPlan 接收 4 个参数:第一个是父级 step($parent),即当前字段所挂载的 step;第二个是目标 step($pgSelect),通常就是该字段自身 plan resolver 的返回结果。需要注意的是,输入对象(input object)上的 applyPlan 仅接收后 3 个参数——除非其上层输入对象或字段参数的 applyPlan 显式向下传递,否则它无法直接访问父级 step。

tip提示

In general, unlike in V4, you should not assume too much about how the SQL will be generated. It's better to use simple methods like $record.get('column_name') to retrieve attributes and then embed these values using $pgSelect.placeholder(...) than it is to make assumptions about the shape of the request and try and be clever and use aliases/etc. Normally @dataplan/pg will be able to figure out the best way to address your needs, and will inline things as necessary/optimal.

总体而言,与 V4 不同,你不应过度预设最终 SQL 会如何生成。与其揣测请求结构并“自作聪明”地手动拼接表别名,不如直接使用 $record.get('column_name') 这类简洁方法获取字段值,再通过 $pgSelect.placeholder(...) 将其嵌入查询中。通常 @dataplan/pg 会自行推导出满足需求的最佳方式,并在合适且最优的时机自动内联相关逻辑。

Examples迁移示例​

Here are some conversions that have taken place on some of the community plugins:

以下是一些社区插件完成 V5 迁移时的改动对比示例: