Skip to main content

wrapPlans

PostGraphile generates plan resolvers automatically for the fields that it generates across your GraphQL API. But sometimes, you want to change what these plans do. Commonly you might want to apply additional filters to a collection, or perform additional actions (or validations) before performing a mutation. Rather than rewriting the field and it's plans from scratch, you can "wrap" the plan that PostGraphile has made with one of your own.

PostGraphile 会为生成的 GraphQL API 字段自动创建对应的 plan resolver。但在实际开发中有时需要调整这些执行计划的行为——例如为集合查询追加额外的过滤条件,或在执行 mutation 前插入额外的操作(或数据校验)。此时无需从零重写整个字段及其执行计划,只需用你自定义的逻辑去“包装(wrap)”PostGraphile 原有的 plan 即可。

wrapPlans helps you to easily generate a "schema plugin" for 'wrapping' the plan resolvers generated by PostGraphile. You can load the resulting schema plugin via your graphile.config.mjs (or similar) preset.

wrapPlans 可以帮助你轻松生成一个“schema 插件”,用于包装 PostGraphile 自动生成的 plan resolver。生成的插件可以通过 graphile.config.mjs(或同类配置文件)中的 preset 进行加载。

Need new fields instead?需要新增字段?

If you are creating new fields or types, extendSchema will get you there faster. Reach for wrapPlans when you want to keep an existing field and only adjust how it plans or resolves.

如果你的需求是添加新字段或新类型,使用 extendSchema 会更加高效;只有当你希望保留现有字段、仅调整它的规划或解析方式时,才适合使用 wrapPlans。

warning警告

Some of the fields in the GraphQL schema expect their parent value to be of a particular step class, so in these cases you must be careful to ensure that you don't break this expectation otherwise planning errors may occur. This is typically not a concern with modifying the result of "leaf" fields (e.g. masking a users email address) since generally these do not depend on the specific step type.

GraphQL schema 中的部分字段会要求其父级返回值属于特定的 step 类;因此在这类场景下进行包装时,务必注意不要破坏该约束,否则可能引发规划阶段报错。而如果你只是修改“叶子(leaf)”字段的返回值(例如对用户邮箱地址做脱敏处理),通常无需担心这一问题,因为叶子字段一般不依赖具体的 step 类型。

Signatures函数签名​

There are two variants of wrapPlans with slightly different signatures (function overloading). These reflect the two methods of calling wrapPlans. If you want to wrap one or two specific resolvers (where you know the type name and field name) then method 1 is a handy shortcut. If, however, you want to wrap a number of resolvers in the same way then the more flexible method 2 is what you want.

wrapPlans 提供了两种重载形式(function overloading),签名略有差异,分别对应两种不同的调用方式:如果你明确知道类型名和字段名,只想包装一两个特定字段的 resolver,方式一是最顺手的快捷方式;但如果你想按统一规则批量包装一批 resolver,则应选用更灵活的方式二。

// Method 1: wrap individual resolvers of known fields
function wrapPlans(
rulesOrGenerator: PlanWrapperRules | PlanWrapperRulesGenerator,
options?: WrapPlansOptions,
): GraphileConfig.Plugin;

interface PlanWrapperRules {
[typeName: string]: {
[fieldName: string]: PlanWrapperRule | PlanWrapperFn;
};
}

interface PlanWrapperRule {
/** The plan wrapper function */
plan?: PlanWrapperFn;

/**
* Set false if you don't want us to ensure the fieldArgs have been applied
* when your plan wrapper calls the underlying plan.
*/
autoApplyFieldArgs?: boolean;
}

interface WrapPlansOptions {
/** The name to give this plugin, to make debugging easier */
name?: string;
/** Optional version of the plugin */
version?: string;
/** Optional description of the plugin, to make debugging easier */
description?: string;

/**
* Set this `true` if you know that the given plans will never be called in
* the context of resolver emulation, and thus wrapping `defaultPlanResolver`
* will not cause issues.
*
* @see {@link https://err.red/pwpr}
*
*/
disableResolverEmulationWarnings?: boolean;
}

type PlanWrapperFn = (
plan: SmartFieldPlanResolver,
$source: Step,
fieldArgs: FieldArgs,
info: FieldInfo,
) => any;

type PlanWrapperRulesGenerator = (
build: Partial<GraphileBuild.Build> & GraphileBuild.BuildBase,
) => PlanWrapperRules;

/****************************************/

// Method 2: wrap all resolvers that match a filter function
function wrapPlans<T>(
filter: (
context: GraphileBuild.ContextObjectFieldsField,
build: GraphileBuild.Build,
field: GrafastFieldConfig,
) => T | null,
rule: (match: T) => PlanWrapperRule | PlanWrapperFn,
options?: WrapPlansOptions,
): GraphileConfig.Plugin;

Both signatures accept an optional options argument. Set disableResolverEmulationWarnings: true to silence the resolver emulation warning. This warning is irrelevant when your schema uses only Grafast plan resolvers and contains no traditional resolvers. Read more at wrapPlans resolver emulation warning.

两种签名都接收一个可选的 options 参数。设置 disableResolverEmulationWarnings: true 可关闭 resolver 模拟(emulation)警告——如果你的 schema 全部采用 Grafast plan resolver、不包含任何传统 resolver,那么该警告与你无关。更多详情请参阅 wrapPlans resolver 模拟警告说明。

Method 1: wrapping individual resolvers of known fields方式一:包装已知字段的单个 resolver​

// Method 1: wrap individual resolvers of known fields
function wrapPlans(
rulesOrGenerator: PlanWrapperRules | PlanWrapperRulesGenerator,
options?: WrapPlansOptions,
): GraphileConfig.Plugin;

In this method, wrapPlans takes either the resolver wrapper rules object directly, or a generator for this rules object, and returns a plugin.

在这种方式下,wrapPlans 直接接收一个 resolver 包装规则对象(或返回该规则对象的生成器函数),并返回一个插件。

Example: convert to lower case示例:转换为小写​

import { wrapPlans } from "postgraphile/utils";
import { lambda } from "postgraphile/grafast";

export default wrapPlans({
User: {
email(plan) {
const $email = plan();
return lambda($email, (email) => email.toLowerCase());
},
},
});

Example: multiple fields示例:同时包装多个字段​

When there's an explicit list of fields that you want to wrap in the same way, this method can still be useful:

如果你有一份明确的字段清单,且希望以相同的方式包装它们,方式一依然非常实用:

import { sideEffect } from "postgraphile/grafast";

function assertValidUserData(data) {
if (!data || data.username?.length === 0) {
throw new Error("Invalid data");
}
}

const validateUserData = (propName) => {
return (plan, $source, fieldArgs) => {
const $user = fieldArgs.getRaw(["input", propName]);

// Callback throws error if invalid
sideEffect($user, (user) => assertValidUserData(user));

return plan();
};
};

export default wrapPlans({
Mutation: {
createUser: validateUserData("user"),
updateUser: validateUserData("userPatch"),
updateUserById: validateUserData("userPatch"),
updateUserByEmail: validateUserData("userPatch"),
},
});

Rules object规则对象(Rules object)​

The rules object is a two-level map of typeName (the name of a GraphQLObjectType) and fieldName (the name of one of the fields of this type) to either a rule for that field, or a resolver wrapper function for that field. The generator function accepts the Build object which can sometimes be useful, e.g. to get the preset's schema options, or to retrieve things from the registry.

规则对象是一个两层嵌套的映射结构,以 typeName(GraphQLObjectType 的名称)作为第一层键、fieldName(该类型下的某个字段名)作为第二层键,对应的值可以是该字段的包装规则对象,也可以直接是 resolver 包装函数。规则生成器函数会接收 Build 对象作为参数,这在需要读取 preset 的 schema 选项或从 registry 中检索信息时非常有用。

interface PlanWrapperRules {
[typeName: string]: {
[fieldName: string]: PlanWrapperRule | PlanWrapperFn;
};
}

type PlanWrapperRulesGenerator = (
build: Partial<GraphileBuild.Build> & GraphileBuild.BuildBase,
) => PlanWrapperRules;

关于 plan resolver 包装函数的详细说明,请参阅下文“Plan resolver 包装函数”。

Example: null email unless own示例:仅本人可见邮箱,否则返回 null​

For example, this plugin wraps the User.email field, returning null if the user requesting the field is not the same as the user for which the email was requested. (Note that the email is still retrieved from the database, it is just not returned to the user.)

例如,下面这个插件包装了 User.email 字段:当发起请求的用户与被查询邮箱所属的用户不是同一人时,返回 null。(请注意,邮箱数据仍会从数据库中查出,只是在结果中不返回给调用方。)

import { wrapPlans } from "postgraphile/utils";
import { context, lambda } from "postgraphile/grafast";

export default wrapPlans({
User: {
email(plan, $user) {
const $userId = $user.get("id");
const $currentUserId = context().get("jwtClaims").get("user_id");
const $email = plan();
return lambda(
[$userId, $currentUserId, $email],
([userId, currentUserId, email]) =>
userId === currentUserId ? email : null,
);
},
},
});

Example: mask email示例:对邮箱地址脱敏​

This example uses the default resolver of the User.email field to get the actual value, then masks the value instead of omitting it.

此示例同样通过 User.email 字段的默认 resolver 获取原始邮箱值,但不是直接隐藏,而是将其脱敏后再返回。

import { wrapPlans } from "postgraphile/utils";
import { lambda } from "postgraphile/grafast";

export default wrapPlans({
User: {
email(plan) {
const $email = plan();
return lambda($email, (email) =>
// someone@sub.example.com -> so***@su***.com
email.replace(
/^(.{1,2})[^@]*@(.{,2})[^.]*\.([A-z]{2,})$/,
"$1***@$2***.$3",
),
);
},
},
});

Method 2: wrap all resolvers matching a filter方式二:包装所有匹配过滤器的 resolver​

function wrapPlans<T>(
filter: (
context: GraphileBuild.ContextObjectFieldsField,
build: GraphileBuild.Build,
field: GrafastFieldConfig,
) => T | null,
rule: (match: T) => PlanWrapperRule | PlanWrapperFn,
options?: WrapPlansOptions,
): GraphileConfig.Plugin;

In this method, wrapPlans takes two function arguments. The first function is a filter that is called for each field; it should return a truthy value if the field is to be wrapped (or null otherwise). The second function is called for each field that passes the filter, it will be passed the return value of the filter and must return a resolve wrapper function or rule (see plan resolver wrapper functions below).

在这种方式下,wrapPlans 接收两个函数作为参数。第一个函数是过滤器,系统会针对每个字段调用它——若该字段需要被包装,过滤器应返回一个真值(truthy value),否则返回 null。第二个函数则只针对通过过滤器的字段调用,它会收到过滤器的返回值作为参数,并必须返回一个 resolver 包装函数或包装规则对象(详见下文的 plan resolver 包装函数)。

The filter is called with the following arguments:

过滤器函数在调用时会收到以下参数:

  • context: the Context value of the field, the context.scope property is the most likely to be used

    context:该字段对应的 Context 对象,其中最常用的是 context.scope 属性

  • build: the Build objects which contains a lot of helpers

    build:Build 对象,内部包含大量辅助工具

  • field: the field specification itself

    field:字段本身的配置定义

The value you return can be any arbitrary truthy value, it should contain anything from the above arguments that you need to create your resolver wrapper.

过滤器可以返回任意真值,你可以将后续构造 resolver 包装器所需的上述参数信息一并放入该返回值中传递下去。

import { wrapPlans } from "postgraphile/utils";
import { sideEffect } from "postgraphile/grafast";

// Example: log before and after each mutation runs
export default wrapPlans(
(context) => {
if (context.scope.isRootMutation) {
return { scope: context.scope };
}
return null;
},
({ scope }) =>
(plan, _, fieldArgs) => {
sideEffect(fieldArgs.getRaw(), (args) => {
console.log(
`Mutation '${scope.fieldName}' starting with arguments:`,
args,
);
});

const $payload = plan();

sideEffect($payload, (payload) => {
console.log(`Mutation '${scope.fieldName}' payload:`, payload);
});

return $payload;
},
);
Mutations typically return object({ result: $step })Mutation 通常返回 object({ result: $step })

For built-in CRUD mutations and function mutations, the plan returned by the field is an object step containing a result property. The underlying mutation step (e.g. insert/update/delete or function call) lives at result so you can write const $result = $payload.get("result") consistently across mutation types. This consistency is intentional for plugin authors, and the object wrapper also leaves room for additional payload fields in future without breaking existing plans.

对于内置的 CRUD mutation 以及函数 mutation,字段返回的 plan 都是一个包含 result 属性的 object step。底层的变更操作 step(如 insert/update/delete 或数据库函数调用)就存放在 result 中,因此你可以在各类 mutation 之间统一使用 const $result = $payload.get("result") 来获取它。这种结构一致性是专门为方便插件作者而设计的,同时外层的对象包装也为日后新增更多 payload 字段预留了扩展空间,不会破坏现有执行计划。

Plan resolver wrapper functionsPlan resolver 包装函数​

A resolver wrapper function is similar to a Grafast plan resolver, except it takes an additional argument (at the start) which allows delegating to the plan resolver that is being wrapped. If and when you call the plan function, you may optionally pass one or more of the arguments $source, fieldArgs, info; these will then override the values that the resolver will be passed. Calling plan() with no arguments will just pass through the original values unmodified.

Plan resolver 包装函数的写法与普通的 Grafast plan resolver 非常相似,唯一区别在于它的首位多了一个额外参数(即 plan),用于委托调用被包装的原 plan resolver。在调用 plan 函数时,你可以选择性地传入 $source, fieldArgs, info 中的一个或多个参数,用来覆盖原本要传给原 plan resolver 的对应值;如果直接不带参数地调用 plan(),则会原封不动地透传原始参数。

type PlanWrapperFn = (
plan: SmartFieldPlanResolver,
$source: Step,
fieldArgs: FieldArgs,
info: FieldInfo,
) => any;