Skip to main content

extendSchema

extendSchema is the plugin generator you need to know about. It’s the “bread and butter” of customizing your PostGraphile schema, enabling you to add new fields and types to your GraphQL schema in a convenient and concise familiar syntax — GraphQL SDL.

extendSchema 是自定义 PostGraphile schema 时最核心、最常用的插件生成器。它让你能够用简洁直观、大家都很熟悉的语法——GraphQL SDL——便捷地向 GraphQL schema 中添加新字段与新类型。

The SDL is not validated系统不会校验 SDL

Though the SDL syntax is used, it is not validated — if you define a type but never use that type, that will likely not cause a schema validation error. If you use a directive that does not exist (or pass the wrong arguments to a directive), that’s also unlikely to error. The SDL is just used as a convenient syntax, it is converted under the hood into schema hooks as if you had written a Graphile Build plugin by hand.

虽然这里使用了 SDL 语法,但框架并不会对其进行校验——即使定义了某个类型却从未使用,通常也不会触发 schema 校验错误;即便使用了不存在的指令(或传错指令参数),也多半不会报错。SDL 在这里只是一种便捷的声明语法,底层会将其转换为等价的 schema hooks,效果与手写 Graphile Build 插件无异。

If you’re already familiar with the typeDefs/resolvers pattern used by systems such as graphql-tools then using extendSchema should feel familiar for you.

如果你此前用过 graphql-tools 等工具中的 typeDefs/resolvers 写法,那么上手 extendSchema 会倍感亲切。

Signature函数签名​

extendSchema is called with a single parameter: a callback function. This function will be passed the build object, and it must return (synchronously) an object defining typeDefs, and one or more of plans and/or resolvers.

extendSchema 接收一个回调函数作为唯一参数。该函数会收到 build 对象,且必须同步返回一个配置对象,其中需要包含 typeDefs,以及 plans 和/或 resolvers 中的一项或多项。

The build argument to the extendSchema callback contains lots of information and helpers defined by various plugins, in particular the registry (build.input.pgRegistry) which contains all the resources and codecs from introspection, the inflection functions (build.inflection), and the SQL helper (build.sql) which is an instance of pg-sql2.

传给 extendSchema 回调的 build 参数汇聚了各插件提供的大量信息与辅助工具,其中最核心的包括:包含 introspection 所得全部 resource 与 codec 的 registry(build.input.pgRegistry)、命名推导 inflection 函数集合(build.inflection),以及作为 pg-sql2 实例的 SQL 辅助工具(build.sql)。

The callback should return an object with the following keys:

回调函数返回的对象应包含以下属性:

  • typeDefs: a string in GraphQL schema definition language (SDL) or a GraphQL AST generated with the gql helper from postgraphile/utils (note this is NOT from the graphql-tag library, ours works in a slightly different way).

    typeDefs:一段 GraphQL schema 定义语言(SDL)字符串,或是通过 postgraphile/utils 提供的 gql 辅助函数生成的 GraphQL AST(请注意,该 gql 并非来自 graphql-tag 库,其工作方式略有不同)。

  • plans (optional, recommended): an object keyed by GraphQL type name that you’re adding or extending in typeDefs, the values of which are objects keyed by the fieldName you’ve added, and the value of which is typically a plan resolver function (although it can be an object that defines both this and other details)

    plans(可选,推荐):以 typeDefs 中新增或扩展的 GraphQL 类型名为键的对象;其值为以新增字段名为键的子对象,子对象的属性值通常是一个 plan resolver 函数(也可以是一个同时定义 plan resolver 及其他配置项的对象)。

  • resolvers (optional, not recommended): like plans, except the functions are a traditional resolver functions rather than plan resolver functions

    resolvers(可选,不推荐):结构与 plans 类似,但其中的函数是传统 resolver 函数,而非 plan resolver 函数。

Use Plans, not Resolvers优先使用 Plans,而非 Resolvers

Unlike in PostGraphile v4, the fourth argument to the resolver functions in resolvers does not contain Graphile Build-related helpers. Since the lookahead system from V4 has been replaced by Grafast query planning, you should use plans rather than resolvers.

与 PostGraphile v4 不同,resolvers 中传统 resolver 函数的第四个参数不再包含 Graphile Build 相关的辅助工具。由于 V4 中的 lookahead 机制已被 Grafast 查询规划所取代,请优先使用 plans 而非 resolvers。

Example示例​

import { extendSchema } from "postgraphile/utils";
import { constant } from "postgraphile/grafast";

export const MyPlugin = extendSchema((build) => {
// Get any helpers we need from `build`
const { sql, inflection } = build;

return {
typeDefs: /* GraphQL */ `
extend type Query {
meaningOfLife: Int
}
`,

objects: {
Query: {
plans: {
meaningOfLife() {
return constant(42);
},
},
},
},

/*
// Though extendSchema and Grafast both support traditional
// resolvers, plan resolvers are preferred for a "pure" Grafast schema.
// Here's what the above would look like with traditional resolvers:
resolvers: {
Query: {
meaningOfLife() {
return 42;
},
},
},
*/
};
});

The gql helpergql 辅助函数​

The gql helper, usage of which is optional, is responsible for turning the human-readable GraphQL schema language you write into an abstract syntax tree (AST) that the application can understand. Our gql help differs slightly from the one you may be familiar with in the graphql-tag npm module, namely in how the placeholders work. Ours is designed to work with PostGraphile’s inflection system, so you can embed strings directly. You may also embed other gql tags directly. For example:

gql 辅助函数是可选的,用于将人类可读的 GraphQL schema 语言转换为程序可解析的抽象语法树(AST)。我们的 gql 与你可能熟悉的 graphql-tag npm 模块略有差异,主要体现在插值占位符的处理上:PostGraphile 的 gql 专为配合 inflection 系统而设计,允许直接嵌入字符串,也支持直接嵌套其他 gql 模板标签。例如:

const nameOfType = "MyType"; // Or use the inflection system to generate a type

// This tag interpolates the string `nameOfType` to allow dynamic naming of the
// type.
const Type = gql`
type ${nameOfType} {
str: String
int: Int
}
`;

// This tag interpolates the entire definition in `Type` above.
const typeDefs = gql`
${Type}

extend type Query {
fieldName: Type
}
`;

Type-level fields类型级配置字段​

Object type step assertion对象类型的 step 断言​

Object types in Grafast can indicate that they must be represented by a particular step or one of a set of steps; this can help to catch bugs early. For example, in PostGraphile a database table resource should be represented by a pgSelectSingle or similar class; representing it with object({id: 1}) or similar would mean the step doesn’t have the expected helper methods and downstream fields may fail to plan because their expectations are broken.

Grafast 中的对象类型可以声明其必须由特定的 step(或某几个 step 类之一)来表示,这有助于尽早暴露潜在 bug。例如,在 PostGraphile 中,数据库表 resource 应当由 pgSelectSingle 或类似 step 类表示;如果误用 object({id: 1}) 等 step 来表示,它就会缺少预期的辅助方法,导致下游字段因前置假设不成立而在规划阶段失败。

Object types’ plans entries may define an assertStep property to indicate the type of step the object type’s fields’ resolvers will be expecting; this is equivalent to typeConfig.extensions.grafast.assertStep when defining a object type programmatically.

对象类型的配置项中可以定义 assertStep 属性,用来指明该类型下各字段的 resolver 所期望接收的 step 类型;这与以编程方式定义对象类型时设置 typeConfig.extensions.grafast.assertStep 是等价的。

The value for assertStep can either be a step class itself (e.g. PgSelectSingleStep) or it can be an “assertion function” that throws an error if the passed step is not of the right type, e.g.:

assertStep 的值既可以直接是一个 step 类(如 PgSelectSingleStep),也可以是一个“断言函数”——当传入的 step 不符合预期类型时抛出错误,例如:

import { extendSchema } from "postgraphile/utils";

const schema = extendSchema({
typeDefs: /* GraphQL */ `
type MyObject {
id: Int
}
`,
objects: {
MyObject: {
assertStep($step) {
if ($step instanceof PgSelectSingleStep) return true;
if ($step instanceof PgInsertSingleStep) return true;
if ($step instanceof PgUpdateSingleStep) return true;
throw new Error(
`Type 'User' expects a step of type PgSelectSingleStep, PgInsertSingleStep ` +
`or PgUpdateSingleStep; but found step of type '${$step.constructor.name}'.`,
);
},
plans: {
a($obj: PgSelectSingleStep | PgInsertSingleStep | PgUpdateSingleStep) {
return $obj.get("id");
},
},
},
},
});

Type and field scopes类型与字段的 scope​

Graphile Build plugins use the “scope” that a type/field/argument/etc is defined with in order to determine whether or not to hook that entity and augment it. For example, the builtin PgFirstLastBeforeAfterArgsPlugin will automatically add first, last, before and after arguments to fields that are scoped as isPgFieldConnection: true and have an associated and suitable pgFieldResource scope set.

Graphile Build 插件会根据类型、字段、参数等实体在定义时附带的“scope”信息,来决定是否对其触发 hook 并进行增强。例如,内置的 PgFirstLastBeforeAfterArgsPlugin 会自动为带有 isPgFieldConnection: true 且关联了合适 pgFieldResource scope 的字段添加 first、last、before 和 after 参数。

You can add to/overwrite the Graphile Build “scope” of a type by adding the scope property to the object’s plans object.

要在类型级别补充或覆盖 Graphile Build 的“scope”,只需在对象配置中添加 scope 属性即可。

You can add to/overwrite the Graphile Build scope of a field by making the field definition an object (if it was previously a function, move the function to be inside the object using the plan key) and adding the scope property.

要补充或覆盖某个字段的 Graphile Build scope,可以把该字段的定义改写为一个对象(如果原本是一个函数,将其移至该对象下的 plan 属性中),然后添加 scope 属性。

For example:

示例如下:

import { extendSchema } from "postgraphile/utils";

const schema = extendSchema((build) => {
const { users } = build.pgResources;
return {
typeDefs: /* GraphQL */ `
type MyObject {
id: Int
}
`,
objects: {
MyObject: {
// Graphile Build "scope" for the object type 'MyObject'
scope: {
pgTypeResource: users,
},
plans: {
id: {
// The Graphile Build "scope" for the 'MyObject.id' field
scope: {
pgFieldAttribute: users.codec.attributes.id,
},

// The plan resolver for the 'MyObject.id' field
plan($obj) {
return $obj.get("id");
},
},
},
},
},
};
});
It is possible to unset or overwrite automatic scopes可以覆盖或清除自动推导的 scope

extendSchema might try and guess the scopes to use to be helpful; if it gets them wrong then be sure to overwrite them using the instructions above. To unset scopes, set them to undefined.

为了省事,extendSchema 有时会尝试自动推测所需的 scope;如果它猜错了,请务必按上述方式手动覆盖。若需清除某个 scope,将其值设为 undefined 即可。

Querying the database查询数据库​

You should read the Grafast introduction and the page on “plan resolvers” before reading further here.

继续阅读之前,建议先浏览 Grafast 简介以及“plan resolver”专题页。

Grafast operate based on “steps”, instances of step classes, returned from “plan resolvers”. Though there are many different step classes, most will accept as input any other step, no matter the class.

Grafast 的核心机制围绕“step”(由 plan resolver 返回的 step 类实例)运转。虽然 step 类种类繁多,但大多数 step 都能接受任意类型的其他 step 作为输入。

However, the plan resolvers attached to the fields on a GraphQL type will typically expect the incoming step to be of the right class, otherwise it will not have the expected methods on it. For example, all the fields on a GraphQL object type that PostGraphile has generated from a database table will expect the parent step to be a PgSelectSingleStep instance (or similar) so that they may do things like $row.get('avatar_url') and have that access the relevant column in the database.

不过,挂载在某个 GraphQL 类型各字段上的 plan resolver 通常要求传入的父级 step 属于特定类型,否则上面就没有预期的方法可供调用。例如,PostGraphile 基于数据库表生成的 GraphQL 对象类型,其所有字段都要求父级 step 是 PgSelectSingleStep 实例(或类似 step),这样才能通过 $row.get('avatar_url') 读取对应的数据库列。

Thus, what you do inside your plan resolver and what you return from your plan resolver are two different concerns. It’s essential that you return the right class of step from your plan resolver, to be compatible with what the schema is expecting, but you have a lot of freedom within your plan resolver as to how to achieve that.

因此,“plan resolver 内部做什么”和“最终返回什么”是两码事:返回值必须符合目标 schema 类型所期望的 step 类,至于内部如何组织逻辑去拿到这个 step,则有很大的自由度。

One common desire is to access the data in the GraphQL context. You can access this in Grafast using the context() step; for example, you may have stored the current user’s ID on the GraphQL context via the userId property, to retrieve these you might do this in your plan resolver function:

一个常见需求是访问 GraphQL 上下文中的数据。在 Grafast 中可以使用 context() step 来获取:例如,假设你把当前用户的 ID 存放在 GraphQL 上下文的 userId 属性中,在 plan resolver 函数里可以这样读取:

const $userId = context().get("userId");

Data from the database can be retrieved using “resources.” Resources can be found on build.pgResources, keyed by their name. For example, if you have organizations, users and channels tables, you can get the resources for them via:

数据库中的数据可以通过“resource”来查询。所有 resource 都存放在 build.pgResources 上,以其名称作为键名。例如,如果数据库中有 organizations、users 和 channels 三张表,可以这样获取它们对应的 resource:

const { organizations, users, channels } = build.pgResources;

Now that you have a reference to the users resource, inside a plan resolver function you could get a step representing a set of rows using resource.find:

拿到 users resource 的引用后,在 plan resolver 函数内就可以调用 resource.find 来获取代表一组数据行的 step:

const $users = users.find();
// ^ PgSelectStep - represents a set of rows

Or you could get a step representing just a single row via resource.get (the filter argument is required, and must represent a combination of columns that matches a unique constraint):

也可以调用 resource.get 来获取代表单行记录的 step(过滤参数是必填项,且必须对应匹配唯一约束的列组合):

const $user = users.get({ id: $userId });
// ^ PgSelectSingleStep - represents a single row

Now that you have a step representing a single row ($user) you can retrieve its column values using $row.get:

有了代表单行记录的 step($user)之后,就可以使用 $row.get 读取它的列值:

const $organizationId = $user.get("organization_id");

You could then feed this into another step, for example:

接着还可以把这个 step 传给下一个 step,例如:

const $channels = channels.find({ organization_id: $organizationId });

Example示例​

Pulling this all together, you could build a plugin that adds a Query.myChannels field returning all the channels just from your organization:

把以上步骤串联起来,就能编写一个添加 Query.myChannels 字段的插件,只返回当前用户所属组织下的所有频道:

import { extendSchema } from "postgraphile/utils";
import { context } from "postgraphile/grafast";

export const MyChannelsPlugin = extendSchema((build) => {
const { users, channels } = build.pgResources;
return {
typeDefs: /* GraphQL */ `
extend type Query {
myChannels: [Channel]
}
`,
objects: {
Query: {
plans: {
myChannels() {
const $userId = context().get("userId");
const $user = users.get({ id: $userId });
const $orgId = $user.get("organization_id");
const $channels = channels.find({ organization_id: $orgId });
return $channels;
},
},
},
},
};
});
Automatic type generation类型自动生成

The Channel type used in the typeDefs above is the type that PostGraphile generated automatically for the channels table. See Tables for more on the artifacts generated for each database table.

上面 typeDefs 中使用的 Channel 类型,就是 PostGraphile 为 channels 表自动生成的类型。关于每张数据库表会生成哪些类型与字段,请参阅 Tables。

Grafast will optimize the requestsGrafast 会自动优化请求

Though you might be thinking that this would result in multiple requests being issued to the database, thanks to the magic of Grafast and @dataplan/pg, this is not the case. During the optimization phase for the operation plan, @dataplan/pg will recognize that all of these steps represent data coming from the database, and will optimize this into something roughly equivalent to:

你可能会担心这样写会向数据库发出多次请求,但借助 Grafast 与 @dataplan/pg 的优化能力,实际情况并非如此。在操作计划的优化阶段,@dataplan/pg 会识别出这些 step 均来自数据库,并将它们合并优化为大致等价于如下的 SQL 查询:

select ...
from channels
where organization_id = (
select users.organization_id
from users
where users.id = $1
);

Running custom SQL执行自定义 SQL​

As mentioned above, though what we return from the plan resolver is critical, how we get there is less so. If we want, we can replace some of the logic above with our own custom logic, so long as the result of the plan resolver is still a PgSelectStep representing a set of rows.

如前所述,只要 plan resolver 的返回值类型符合预期,内部如何实现则相当灵活。如有需要,我们可以把上述部分逻辑替换为自定义实现,只要最终返回的仍然是代表一组数据行的 PgSelectStep 即可。

One way to issue arbitrary SQL queries against the database is to use the loadOneWithPgClient step, or its cousin loadManyWithPgClient. These both accept an “executor” as the first argument, a step representing arbitrary data as the second argument, and an asynchronous callback as the third argument. The callback will be called with a PgClient instance and the list of resolved data from the step in the second argument, and must return a list of values related to the input data.

向数据库执行任意 SQL 查询的常用方式之一是使用 loadOneWithPgClient 或同系列的 loadManyWithPgClient step。两者均接收三个参数:第一个是“executor”,第二个是代表输入数据的任意 step,第三个是异步回调函数。该回调会收到一个 PgClient 实例以及第二个参数所对应 step 批量解析出的数据列表,并且必须返回与输入列表一一对应的结果列表。

import { normalizePhone } from "@localrepo/normalize-phone-numbers";

export const MyPlugin = extendSchema((build) => {
const { pgExecutor } = build;
return {
typeDefs: /* GraphQL */ `
extend type User {
e164PhoneNumbers: [String]
}
`,
objects: {
User: {
plans: {
e164PhoneNumbers($user) {
const $userId = get($user, "id");
return loadManyWithPgClient(
pgExecutor,
$userId,
async (pgClient, userIds) => {
// NOTE: We're doing batched processing across all the userIds,
// fetching all their phone numbers at once and converting them.

// Step 1 - load the user's phone numbers
const { rows: userContacts } = await pgClient.query<{
user_id: string;
phone: string;
}>({
text: `
select user_id, phone
from user_contacts
where user_id = any($1::int[]);
`,
values: [userIds],
});

// Step 2 - normalize the phone numbers
const phoneNumbersByUserId: Record<string, string[]> = {};
for (const row of userContacts) {
const { user_id: userId, phone: rawPhone } = row;
const normalized = normalizePhone(rawPhone);
(phoneNumbersByUserId[userId] ??= []).push(normalized);
}

// Optionally: query pgClient again using these normalized phone numbers

// Finally - match each input to its corresponding data to form
// the output
return userIds.map(
(userId) => phoneNumbersByUserId[userId] ?? [],
);
},
);
},
},
},
},
};
});
PgClient is an abstractionPgClient 是一层抽象

The PgClient instance is an abstraction provided by @dataplan/pg, it contains common functionality but also any helpers that the specific Postgres adaptor you’re using wishes to expose. Read more about Postgres adaptors in the @dataplan/pg documentation.

PgClient 实例是由 @dataplan/pg 提供的抽象接口,除了通用能力外,还可能包含你当前使用的 Postgres 适配器所暴露的特定辅助方法。在 @dataplan/pg 文档中了解更多关于 Postgres 适配器的信息。

The executorExecutor(执行器)​

What is an executor?

什么是 executor?

It’s the thing that tells Grafast (or, more specifically, @dataplan/pg) how to communicate with the database. Normally it’s embedded directly into the resources, but since we’re doing arbitrary SQL no resource is involved.

它负责告诉 Grafast(更具体地说是 @dataplan/pg)如何与数据库通信。通常 executor 会直接内嵌在各 resource 中,但由于这里执行的是任意自定义 SQL,并未经过任何 resource,因此需要显式提供。

Why is it explicit rather than implicit?

为什么需要显式传入而非隐式获取?

The simple answer for that is that there can be more than one executor, for example if your schema represents more than one PostgreSQL database.

原因很简单:系统中可能存在多个 executor,例如当你的 schema 对接了多个 PostgreSQL 数据库时。

How do I get an executor?

如何获取 executor?

Typically you would want to extract the executor from the resource that you are dealing with, for example:

通常建议直接从你正在处理的 resource 中提取 executor,例如:

const executor = channels.executor;

This is the safest approach. However, if you're not specifically dealing with a resource and wish to communicate with the database directly (e.g. for loadOneWithPgClient()), then you can access the default/primary/main executor via:

这是最稳妥的做法。不过,如果你并未操作具体的 resource,而是希望直接访问数据库(例如配合 loadOneWithPgClient() 使用),也可以通过以下方式获取默认/主 executor:

const executor = build.pgExecutor;

PostGraphile has support for multiple Postgres databases and custom source/executor names via preset.pgServices. All executors are available via the registry; typically (if a user did not rename the default) there’s an executor called main which you can access like this:

PostGraphile 支持通过 preset.pgServices 配置多个 Postgres 数据库以及自定义的 source/executor 名称。所有 executor 都注册在 registry 中;通常情况下(如果未重命名默认配置),会有一个名为 main 的 executor,可以这样获取:

// Normally equivalent to `build.pgExecutor`:
const executor = build.input.pgRegistry.pgExecutors.main;

Reading database column values读取数据库列值​

When extending a schema, it’s often because you want to expose data from Node.js that would be too difficult (or impossible) to access from PostgreSQL. When defining a field on an existing table-backed type defined by PostGraphile, it’s useful to access data from the underlying table in the plan resolver.

扩展 schema 的一个常见原因,是希望暴露一些在 PostgreSQL 内部难以实现(甚至无法实现)的 Node.js 侧数据。而在 PostGraphile 基于数据库表生成的现有类型上定义新字段时,通常需要在 plan resolver 中读取底层表的数据。

To do this you can use the $row.get(columnName) method, where $row is the first parameter passed to your plan resolver function (representing the current record).

为此,可以调用 $row.get(columnName) 方法,其中 $row 是传入 plan resolver 函数的第一个参数(代表当前记录)。

Here’s an example to illustrate:

下面通过一个例子来说明:

In the database you have a product table (imagine an online store), that PostGraphile will include in the GraphQL schema by creating a type Product with fields id, name, price_in_us_cents.

假设你有一个在线商店数据库,其中包含一张 product 表,PostGraphile 会为它在 GraphQL schema 中创建 Product 类型,包含 id、name、price_in_us_cents 等字段。

create table product (
id uuid primary key,
name text not null,
price_in_us_cents integer not null
);

This may result in the following GraphQL type:

它生成的 GraphQL 类型大致如下:

type Product {
id: UUID!
name: String!
priceInUsCents: Int!
}

However, imagine you’re selling internationally, and you want to expose the price in other currencies directly from the Product type itself. This kind of functionality is well suited to being performed in Node.js (e.g. by making a REST call to a foreign exchange service over the internet) but might be a struggle from with PostgreSQL.

现在假设你要面向国际市场销售商品,希望直接在 Product 类型上提供其他币种的价格。这类逻辑非常适合放在 Node.js 中完成(比如通过网络向汇率服务发起 REST 请求),而在 PostgreSQL 内部则很难直接实现。

We’ll retrieve the price_in_us_cents value from the database, and then use the loadOne step to batch-convert these values from USD to AUD:

我们先从数据库中取出 price_in_us_cents 的值,再使用 loadOne step 批量将其从美元(USD)换算为澳元(AUD):

import { extendSchema } from "postgraphile/utils";
import { loadOne } from "postgraphile/grafast";
import { getExchangeRate } from "./myBusinessLogic.mjs";

async function convertUsdToAud(values) {
const usdToAud = await getExchangeRate("USD", "AUD");
return values.map((usd) => usd * usdToAud);
}

export const MyForeignExchangePlugin = extendSchema((build) => {
return {
typeDefs: /* GraphQL */ `
extend type Product {
priceInAuCents: Int!
}
`,
objects: {
Product: {
plans: {
priceInAuCents($product) {
const $cents = $product.get("price_in_us_cents");
return loadOne($cents, convertUsdToAud);
},
},
},
},
};
});

Returning a connection返回 Connection​

When returning a connection in extendSchema, you must be sure that your plan resolver yields a connection(...) step; failure to do this may result in errors such as $connection.getSubplan is not a function.

在 extendSchema 中返回 Connection 时,必须确保 plan resolver 最终返回的是一个 connection(...) step;否则可能会触发 $connection.getSubplan is not a function 之类的错误。

For example, if you want to expose a related ReviewConnection from Product:

例如,若要从 Product 类型上暴露关联的 ReviewConnection:

import { extendSchema } from "postgraphile/utils";
import { connection } from "postgraphile/grafast";

export const MyProductReviewsPlugin = extendSchema((build) => {
const { reviews } = build.pgResources;

return {
typeDefs: /* GraphQL */ `
extend type Product {
reviews: ReviewConnection
}
`,
objects: {
Product: {
plans: {
reviews($product) {
const $productId = $product.get("id");
const $reviews = reviews.find();
$reviews.where(
(sql) => sql`${$reviews}.product_id = ${$productId}`,
);

return connection($reviews);
},
},
},
},
};
});

Updating pgSettings in a mutation在 mutation 中更新 pgSettings​

If your mutation changes the authorization posture of the user (e.g. login, register, logout, viewAsUser, sudo, etc), you may need to update the pgSettings the database connection uses in order to ensure that subsequent fields (such as those on the mutation payload object) resolve with the expected identity and permissions.

如果你的 mutation 会改变用户的鉴权状态(例如 login、register、logout、viewAsUser、sudo 等),你通常需要更新数据库连接所使用的 pgSettings,以确保后续字段(例如 mutation payload 对象上的字段)能够以新的身份与权限进行解析。

To update pgSettings, use a step with side effects (such as a sideEffect() step) to modify the object. An example mutation plan might contain something like:

要更新 pgSettings,可以使用带有副作用的 step(例如 sideEffect() step)来修改该对象。典型的 mutation 规划代码大致如下:

// Or: `import { context, sideEffect } from "postgraphile/grafast";`
const { context, sideEffect } = build.grafast;

// Create the step(s) for your mutation work
const $user = login(/*...*/);

// Then plan to update the GraphQL context with the latest pgSettings
const $ctx = context();
const $userId = get($user, "id");
sideEffect([$ctx, $userId], ([ctx, userId]) => {
ctx.pgSettings["jwt.claims.user_id"] = userId;
});

With these changes, the next time a pgSelect() or similar database step executes, it will do so using the new pgSettings claims; the result: RLS-protected resources queried in subsequent fields will reflect the correct post-mutation permissions.

完成这步修改后,接下来执行 pgSelect() 或类似数据库 step 时就会应用更新后的 pgSettings 声明;这样一来,后续字段查询受 RLS 保护的 resource 时,就能准确反映 mutation 执行后的权限状态。

Mutation ExampleMutation 示例​

You might want to add a custom registerUser mutation which inserts the new user into the database and also sends them an email:

下面演示如何添加一个自定义的 registerUser mutation,在向数据库插入新用户的同时发送欢迎邮件:

import { extendSchema } from "postgraphile/utils";
import { access, constant, object } from "postgraphile/grafast";
import { sideEffectWithPgClientTransaction } from "postgraphile/@dataplan/pg";

export const MyRegisterUserMutationPlugin = extendSchema((build) => {
const { sql, pgResources } = build;

// Get the executor from the "users" DB table:
const { users } = pgResources;
const { executor } = users;

return {
typeDefs: /* GraphQL */ `
input RegisterUserInput {
name: String!
email: String!
bio: String
}

type RegisterUserPayload {
user: User
query: Query
}

extend type Mutation {
registerUser(input: RegisterUserInput!): RegisterUserPayload
}
`,
objects: {
Mutation: {
plans: {
registerUser(_, fieldArgs) {
const $input = fieldArgs.getRaw("input");
const $ctx = context();
const $user = sideEffectWithPgClientTransaction(
executor,
[$input, $ctx],
async (pgClient, [input, ctx]) => {
// Our custom logic to register the user:
const {
rows: [user],
} = await pgClient.query({
text: `
INSERT INTO app_public.users (name, email, bio)
VALUES ($1, $2, $3)
RETURNING *`,
values: [input.name, input.email, input.bio],
});

// Send the email. If this fails then the error will be caught
// and the transaction rolled back; it will be as if the user
// never registered
await mockSendEmail(
input.email,
"Welcome to my site",
`You're user ${user.id} - thanks for being awesome`,
);

// Update the pgSettings to use for subsequent fields to reflect
// the user is logged in:
ctx.pgSettings["jwt.claims.user_id"] = user.id;

// Return the newly created user
return user;
},
);

// To allow for future expansion (and for the `clientMutationId`
// field to work), we'll return an object step containing our data:
return object({ user: $user });
},
},
},

// The payload also needs plans detailing how to resolve its fields:
RegisterUserPayload: {
plans: {
user($data) {
const $user = $data.get("user");
// It would be tempting to return $user here, but the step class
// is not compatible with the auto-generated `User` type, so
// errors will occur. We must ensure that we return a compatible
// step, so we will retrieve the relevant record from the database:

// Get the '.id' property from $user:
const $userId = access($user, "id");

// Return a step representing this row in the database.
return users.get({ id: $userId });
},
query($user) {
// Anything truthy should work for the `query: Query` field.
return constant(true);
},
},
},
},
};
});

Mutation Example with Node ID使用 Node ID 的 Mutation 示例​

In this example we’ll use a GraphQL Global Object Identifier (aka Node ID) to soft-delete an entry from our app_public.items table. We’re also going to check that the user performing the soft-delete is the owner of the record.

本例中,我们将使用 GraphQL 全局对象标识符(即 Node ID)来软删除 app_public.items 表中的一条记录,并校验执行软删除的用户是否为该记录的所有者。

Aside: if you’re interested in soft-deletes, check out @graphile-contrib/pg-omit-archived

顺便一提:如果你对软删除功能感兴趣,可以了解一下 @graphile-contrib/pg-omit-archived。

import { extendSchema } from "postgraphile/utils";
import { context, list, specFromNodeId } from "postgraphile/grafast";
import { sideEffectWithPgClientTransaction } from "postgraphile/@dataplan/pg";

const DeleteItemByNodeIdPlugin = extendSchema((build) => {
// We need the nodeId handler for the Item type so that we can decode the ID.
const handler = build.getNodeIdHandler("Item")!;

// Extract the executor from the items resource
const executor = build.pgResources.items.executor;
// Or `build.pgExecutor` if you know you only have one DB
// Or `build.input.pgRegistry.pgExecutors.main` for a named executor

return {
typeDefs: /* GraphQL */ `
input DeleteItemInput {
id: ID!
}
type DeleteItemPayload {
success: Boolean
}
extend type Mutation {
deleteItem(input: DeleteItemInput!): DeleteItemPayload
}
`,

objects: {
Mutation: {
plans: {
deleteItem(_, fieldArgs) {
// jwtClaims is decrypted jwt token data
const $jwtClaims = context().get("jwtClaims");

// Read the input.id value from the arguments
const $nodeId = fieldArgs.getRaw(["input", "id"]);

// Decode the node ID, to something like: `{ id: $someStep }`
const spec = specFromNodeId(handler, $nodeId);
const $itemId = spec.id;

const $success = sideEffectWithPgClientTransaction(
executor,
// Passing a `list` step allows us to pass more than one dependency
// through to our callback:
list([$jwtClaims, $itemId]),
async (pgClient, [jwtClaims, itemId]) => {
if (!itemId || !jwtClaims?.user_id) {
return false;
}
const {
rows: [row],
} = await pgClient.query(
` UPDATE app_public.items
SET is_archived = true
WHERE id = $1
AND user_id = $2
RETURNING *;`,
[itemId, jwtClaims.user_id],
);
return !!row;
},
);

// Since we're returning this data in the same shape as the payload
// and the payload's fields don't need specific step classes, we don't
// need to implement plan resolvers on the payload.
return object({ success: $success });
},
},
},
},
};
});

Polymorphism mutation example多态 Mutation 示例​

This is a full example of adding a custom registerUser mutation whose payload contains a union of a successful result or two expected error types. It uses a transaction to perform the mutation, and catches errors that happen in that transaction (in which case the transaction will be rolled back) and if they are the known, supported, errors then it will return the given error type.

下面是一个完整示例,展示如何添加自定义的 registerUser mutation,使其 payload 包含一个联合类型(成功结果或两种可预期的错误类型)。该 mutation 在事务中执行数据库操作,并捕获事务内发生的异常(此时事务会自动回滚);若异常属于已知的预期错误,则返回对应的错误类型。

import { sideEffectWithPgClientTransaction } from "@dataplan/pg";
import { extendSchema } from "postgraphile/utils";
import {
ObjectStep,
constant,
object,
Step,
access,
list,
} from "postgraphile/grafast";
import { DatabaseError } from "pg";

export const RegisterUserPlugin = extendSchema((build) => {
const { users } = build.pgResources;
const { executor } = users;
// Or: `const executor = build.input.pgRegistry.pgExecutors.main;`
return {
typeDefs: /* GraphQL */ `
extend type Mutation {
registerUser(input: RegisterUserInput!): RegisterUserPayload
}

input RegisterUserInput {
username: String!
email: String!
}

type RegisterUserPayload {
result: RegisterUserResult
query: Query
}

union RegisterUserResult = User | UsernameConflict | EmailAddressConflict

type UsernameConflict {
message: String!
username: String!
}

type EmailAddressConflict {
message: String!
email: String!
}
`,
objects: {
Mutation: {
plans: {
registerUser(_, { $input: { $username, $email } }) {
const $result = sideEffectWithPgClientTransaction(
executor,
list([$username, $email]),
async (pgClient, [username, email]) => {
try {
const {
rows: [user],
} = await pgClient.query<{
id: string;
username: string;
}>({
text: `
insert into app_public.users (username)
values ($1)
returning *`,
values: [username],
});

await pgClient.query({
text: `
insert into app_public.user_emails(user_id, email)
values ($1, $2)`,
values: [user.id, email],
});

await sendEmail(email, "Welcome!");

return { id: user.id };
} catch (e) {
if (e instanceof DatabaseError && e.code === "23505") {
if (e.constraint === "unique_user_username") {
return {
__typename: "UsernameConflict",
message: `The username '${username}' is already in use`,
username,
};
} else if (e.constraint === "unique_user_email") {
return {
__typename: "EmailAddressConflict",
message: `The email address '${email}' is already in use`,
email,
};
}
}
throw e;
}
},
);

return object({ result: $result });
},
},
},

RegisterUserPayload: {
assertStep: ObjectStep,
plans: {
query() {
// The `Query` type just needs any truthy value.
return constant(true);
},
},
},

UsernameConflict: {
// Since User expects a step, our types must also expect a step. We
// don't care what the step is though.
assertStep: Step,
},
EmailAddressConflict: {
assertStep: Step,
},
},
unions: {
// Planning our polymorphic type
RegisterUserResult: {
planType($obj) {
// Determine the type
const $__typename = lambda($obj, (obj) => {
// If it has typename, use that
if (obj.__typename) return obj.__typename;
// Otherwise, if it has an id it must be a user
if (obj.id != null) return "User";
// Otherwise, no idea!
throw new Error(`Could not determine type`);
});
return {
$__typename,
planForType(t) {
switch (t.name) {
case "UsernameConflict":
case "EmailAddressConflict":
// These types just use their objects directly
return $obj;

case "User": {
// In this case, we need to get the record from the database
// associated with the given user id.
const $id = get($obj, "id");
return users.get({ id: $id });
}
default: {
throw new Error(`Don't know how to plan ${t}`);
}
}
},
};
},
},
},
};
});

async function sendEmail(email: string, message: string) {
/*
Write your email-sending logic here. Note that we recommend you enqueue a
job to send the email rather than sending it directly; if you don't already
have a job queue then check out https://worker.graphile.org
*/
}

Plugin SQL Privileges插件的 SQL 权限​

Plugins access the database with the same privileges as everything else — they are subject to RLS/RBAC/etc. If your database user does not have privileges to perform the action your plugin is attempting to achieve then you may need to create a companion database function that is marked as SECURITY DEFINER in order to perform the action with elevated privileges; alternatively you could use this database function directly — see Custom Mutations for more details.

插件访问数据库时遵循与其他查询完全相同的权限体系——即同样受制于 RLS、RBAC 等限制。如果当前数据库用户没有足够的权限执行插件所需的操作,你可能需要创建一个配套的数据库函数,并将其标记为 SECURITY DEFINER 以在提权状态下执行操作;或者也可以直接把这个数据库函数暴露为自定义 mutation——详见自定义 Mutation。