Skip to main content

No makeWrapResolversPlugin不再使用 makeWrapResolversPlugin

Since PostGraphile V5 no longer uses resolvers, wrapping resolvers is meaningless. And yet! Since we now use plans, you can suddenly do a lot more by wrapping the plans than you ever could by wrapping resolvers — not only does it allow you to affect the data that's returned, it also allows you to change the very plan of what will be done!

由于 PostGraphile V5 不再使用 resolver,包装(wrap)resolver 也就失去了意义。不仅如此,因为现在改用了 plan,通过包装 plan 所能实现的能力比过去包装 resolver 强大得多——你不仅可以影响最终返回的数据,甚至能直接改写后续要执行的整个操作计划!

wrapPlans is the new plugin generator that replaces makeWrapResolversPlugin. It has a similar API, but it's somewhat simplified:

wrapPlans 是替代 makeWrapResolversPlugin 的全新插件生成器。它的 API 风格与后者相似,但更加精简:

  • No need for requires any more, since you can use the methods on steps to get what you need

    不再需要 requires,直接调用 step 上的方法即可获取所需数据

  • No resolveInfo since it's not needed in Grafast

    不再传入 resolveInfo,因为 Grafast 中无需该对象

  • No context (but you can retrieve it via the context() step if you need it)

    不再默认传入 context(如有需要,可通过 context() step 获取)

Now let's look at some of the things you might have used makeWrapResolversPlugin for in the past, and see how to map them into V5.

下面来看看过去常用 makeWrapResolversPlugin 实现的几种典型场景,以及它们在 V5 中的对应写法。

Setting a create/update mutation column value在创建/更新 mutation 中设置列值​

You could use makeWrapResolversPlugin in V4 as a clumsy workaround to set specific column values in a built-in CRUD mutation by overriding what the system thought the arguments were. Fortunately, V5's plan system means that you no longer need to do this and you can address the problem more directly — you don't even have to have the column in your GraphQL schema in order to set it any more! 😅

在 V4 中,如果你想在内置的 CRUD mutation 里设置特定列的值,只能借助 makeWrapResolversPlugin 通过覆写参数的方式曲线救国。好在 V5 的 plan 体系让你可以直截了当地解决这个问题——甚至不需要将该列暴露在 GraphQL schema 中,也能直接为它赋值!😅

wrapPlans({
Mutation: {
// This same pattern works for 'update' mutations too
createPost(plan, $source, { $firstName, $lastName }) {
// Call the original plan
const $planResult = plan();

// Get a reference to the `PgInsertSingleStep`.
// Remember: it's a step, it has not executed yet, so we can still
// augment what it will do.
const $insert = $planResult.get("result");

// We have a legacy 'name' field that needs populating; build it from
// each tuple of firstName/lastName fields:
const $name = lambda(
[$firstName, $lastName],
([firstName, lastName]) => `${firstName} ${lastName}`,
// Our callback is synchronous and won't throw
true,
);

// Now set this as the value of 'name' in the PgInsertSingleStep:
$insert.set("name", $name);

// Our result is the same as before (otherwise dependent plans may fail)
return $planResult;
},
},
});

Performing an access check before a field plan在字段 plan 执行前进行访问权限检查​

Steps that have side effects never get tree shaken or de-duplicated, so if we want to throw an error before the mutation takes place we can do so like this:

具有副作用(side effect)的 step 永远不会被 tree-shaking 裁剪或去重,因此如果需要在 mutation 执行前抛出错误,可以像下面这样编写:

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

const plugin = wrapPlans({
Mutation: {
createUser(plan) {
// Extract the 'isAdmin' property from the GraphQL context
const $isAdmin = context().get("isAdmin");

// If the user isn't an admin, throw an error
const $preCheck = sideEffect($isAdmin, (isAdmin) => {
if (!isAdmin) {
throw new Error("Abort");
}
});

// Now call the underlying plans; these will never execute if the above throws
return plan();
},
},
});
warning警告

Plans with side effects are only expected/supported in field plans on the Mutation type. Side effect plans elsewhere may lead to unexpected results.

带有副作用的 plan 仅适用于(且仅支持用于)Mutation 类型的字段 plan。在其他位置使用副作用 plan 可能会导致不可预期的结果。

Manipulating the data a field will return处理字段返回的数据​

It's quite common for developers to store a users email into the users table (see tip below on why you shouldn't do this). You typically wouldn't want other users to be able to see someone's email address; so you could mask it out with a field plan wrapper:

许多开发者习惯把用户的 email 直接存进 users 表(至于为什么不建议这样做,请见下方提示)。通常你不会希望其他用户看到别人的邮箱地址,因此可以通过包装字段 plan 来屏蔽该字段:

const plugin = wrapPlans({
User: {
email(plan, $user, args, info) {
// Get 'userId' from the GraphQL context
const $myUserId = context().get("userId");

// Get the user's ID
const $theirUserId = $user.get("id");

// Get the email via the original plan
const $email = plan();

// Now return a new plan that only returns the email if the IDs match
return lambda(
[$myUserId, $theirUserId, $email],
([myUserId, theirUserId, email]) => {
if (myUserId === theirUserId) {
return email;
} else {
return null; // TODO: ensure the 'email' field is nullable!
}
},
);
},
},
});
tip提示

In my opinion, storing the email onto the users table is generally a bad design pattern. One reason is that it complicates security (see warning below), another reason is plurality: it's a lot harder to go from 1 to 2 of something than it is to go from 2 to 3. You should design your system to allow users to have more than one email address even if you don't allow it to start with, for example by storing emails into a user_emails table.

在我看来,把 email 直接存放在 users 表中通常是一个糟糕的设计。一方面这会让权限控制变得复杂(参见下方危险提示);另一方面还要考虑多值扩展性——把数量限制从 1 改成 2,往往比从 2 改成 3 困难得多。即使系统初期只允许绑定一个邮箱,在设计上也应为多邮箱预留空间,例如将邮箱单独存放在 user_emails 表中。

danger危险

Though the above example may mask the email field when fetched directly, there are side channel attacks that someone could use to determine someones email - for example they could order by the email address and extract it from the cursor, or they could use advanced filtering to perform a dictionary search for the users email address. We strongly advise that you store email addresses and other private information into a separate table for the best security.

尽管上述示例可以在直接查询时屏蔽 email 字段,但攻击者仍可能通过侧信道手段推断出他人的邮箱——例如按邮箱地址排序并从返回的 cursor 中提取信息,或者借助高级过滤功能对用户邮箱进行字典枚举。为了获得最佳的安全性,我们强烈建议将邮箱地址及其他敏感信息存放在独立的表中。