Skip to main content

GraphQL SubscriptionsGraphQL 订阅(Subscriptions)

Subscriptions notify you when an event occurs on the server side. PostGraphile supports subscriptions out of the box (assuming you are using it with a supported webserver), but you are responsible for adding subscription fields to your schema — without any subscription fields, the subscription operation is not possible.

订阅(Subscription)会在服务端发生事件时主动向客户端推送通知。PostGraphile 开箱即支持订阅能力(前提是搭配受支持的 Web 服务器使用),但你需要自行向 schema 中添加订阅字段——如果没有任何订阅字段,subscription 操作就无法使用。

WebsocketsWebSocket 支持​

The most common transport for GraphQL subscriptions is via Websockets. To enable or disable websocket support in your API, use the preset.grafserv.websockets option:

GraphQL 订阅最常用的传输协议是 WebSocket。要在 API 中开启或关闭 WebSocket 支持,请配置 preset.grafserv.websockets 选项:

graphile.config.mjs
export default {
//...
grafserv: {
websockets: true,
},
};
info说明

The endpoint for subscriptions is the same as for GraphQL, except the protocol is changed from http or https to ws or wss respectively.

订阅使用的端点地址与普通 GraphQL 接口相同,只需将协议由 http 或 https 分别替换为 ws 或 wss。

Adding subscription fields添加订阅字段​

The easiest way to add subscription fields is by using extendSchema to extend the Subscription type and add your field. Your subscription fields will typically leverage the Grafast listen() step to subscribe to events on a pubsub-capable entity.

添加订阅字段最简单的方式,是通过 extendSchema 扩展 Subscription 类型并加入所需字段。订阅字段通常会借助 Grafast 的 listen() step,向支持发布/订阅(pubsub)的对象订阅事件。

subscribePlan() and plan()subscribePlan() 与 plan()​

Unlike the rest of your schema where you typically use the plan() plan resolver, for subscriptions we need two plan resolvers: subscribePlan() which will return a streamable step (essentially wrapping an async iterable), and plan() which will take the payload of each of the events from this stream and convert them into something that the subscription result type can use.

与 schema 中其他地方通常只需编写 plan() 不同,订阅字段需要两个 plan resolver:subscribePlan() 负责返回一个可流式读取的 step(本质上封装了一个异步可迭代对象),而 plan() 则负责接收该事件流中每条事件的 payload,并将其转换为订阅返回类型所需的数据形态。

pgSubscriberpgSubscriber​

By default (if your PostgreSQL adaptor supports it), PostGraphile will add a pgSubscriber entry to your GraphQL context. This object is pubsub-capable and uses Postgres' LISTEN/NOTIFY functionality, which is probably the easiest way to get started. You can build a step that represents it in your subscribePlan() resolver via:

默认情况下(只要所使用的 PostgreSQL 适配器支持),PostGraphile 会向 GraphQL 上下文中注入一个 pgSubscriber 属性。该对象具备 pubsub 能力,底层基于 Postgres 的 LISTEN/NOTIFY 机制,通常是最容易上手的起步方案。在 subscribePlan() resolver 中,可以这样构造代表它的 step:

const $pgSubscriber = context().get("pgSubscriber");
tip提示

You can use any pubsub-capable provider with PostGraphile or Grafast: redis, MQTT, EventEmitter, etc; all you need is an abstraction that conforms to the expected interface. See the listen() documentation for specifics.

PostGraphile 和 Grafast 可以搭配任意具备 pubsub 能力的底层方案(如 Redis、MQTT、EventEmitter 等),只需提供一层符合约定接口的抽象封装即可。具体要求请参阅 listen() 文档。

Subscription topic订阅主题(Topic)​

You will also need a topic to listen on. PostgreSQL topics are limited to 63 characters. This topic can be anything you like within PostgreSQL's constraints, but it's typically useful to include the primary key of the entity you're subscribing to in it. In the example below we'll use forum:FORUM_ID:message as the topic for when a new message is posted to a forum, substituting FORUM_ID for the id of the forum that we're interested in (whether this is an int or a UUID it shouldn't go over the 63 character limit).

你还需要指定一个用于监听的主题(topic)。PostgreSQL 对通知通道名的长度限制为最多 63 个字符。在满足 PostgreSQL 限制的前提下,topic 可以任意命名,但通常建议把所订阅实体的主键包含在内。下面的示例将使用 forum:FORUM_ID:message 作为某版块发布新消息时的通知 topic,其中 FORUM_ID 会替换为目标版块的 ID(无论是整数还是 UUID,拼接后的总长度都不会超过 63 个字符的上限)。

Example示例​

The following is an example pulling it all together. In this example when a new message is created an event will be sent to forum:FORUM_ID:message containing the payload {"event": "create", "sub": FORUM_ID, "id": MESSAGE_ID}. This event will be picked up by the pgSubscriber, which listen() subscribes to. This event will then be parsed by listen() using the jsonParse method, and the resulting object will be passed to the Subscription.forumMessage.plan() plan resolver, which does no further processing. The data then flows down to the ForumMessageSubscriptionPayload field steps, which will extract the details that they care about and use them to provide the relevant data to the user.

下面把前面介绍的各个部分串联成一个完整示例。每当有新消息创建时,系统会向 forum:FORUM_ID:message 发送一条事件,其 payload 为 {"event": "create", "sub": FORUM_ID, "id": MESSAGE_ID}。listen() 通过订阅 pgSubscriber 捕获该事件,随后使用 jsonParse 对其解析,并将得到的对象传给 Subscription.forumMessage.plan() plan resolver(本例中它直接原样透传)。接着数据会继续流向 ForumMessageSubscriptionPayload 类型的各个字段 step,由它们提取各自所需的属性并最终返回给客户端。

import { extendSchema } from "postgraphile/utils";
import { context, lambda, listen } from "postgraphile/grafast";
import { jsonParse } from "postgraphile/@dataplan/json";

const MySubscriptionPlugin = extendSchema((build) => {
const { messages } = build.pgResources;
return {
typeDefs: /* GraphQL */ `
extend type Subscription {
forumMessage(forumId: Int!): ForumMessageSubscriptionPayload
}

type ForumMessageSubscriptionPayload {
event: String
message: Message
}
`,
objects: {
Subscription: {
plans: {
forumMessage: {
subscribePlan(_$root, args) {
const $pgSubscriber = context().get("pgSubscriber");
const $forumId = args.get("forumId");
const $topic = lambda($forumId, (id) => `forum:${id}:message`);
return listen($pgSubscriber, $topic, jsonParse);
},
plan($event) {
return $event;
},
},
},
},
ForumMessageSubscriptionPayload: {
plans: {
event($event) {
return $event.get("event");
},
message($event) {
const $id = $event.get("id");
return messages.get({ id: $id });
},
},
},
},
};
});

Triggering subscriptions manually手动触发订阅​

You can use the NOTIFY keyword or pg_notify function in PostgreSQL to trigger an event. For example, you might simulate an event for creating message 27 within forum 1 with:

在 PostgreSQL 中,可以通过 NOTIFY 语句或 pg_notify 函数来触发事件。例如,要模拟在版块 1 中创建消息 27 的事件,可以执行:

NOTIFY "forum:1:message", '{"event": "create", "sub": 1, "id": 27}';

Triggering subscriptions automatically自动触发订阅​

I'm using a fairly complex PostgreSQL function so that I can just use CREATE TRIGGER to trigger events in future without having to define a function for each trigger. Click this paragraph to expand and see the function.下面展示一个相对通用的 PostgreSQL 触发器函数:配置好它之后,后续只需使用 CREATE TRIGGER 即可触发订阅事件,而不必为每个触发器单独编写函数。点击此处展开查看函数定义。

IMPORTANT: this trigger assumes that the primary key for your tables is always id. If this is not the case, you should delete the line containing 'id', v_record.id.

重要提示:该触发器函数默认假设所有表的主键列名均为 id。如果实际情况并非如此,请删去包含 'id', v_record.id 的那一行。

create function tg__graphql_subscription() returns trigger
language plpgsql
as $_$
declare
v_process_new bool = (TG_OP = 'INSERT' OR TG_OP = 'UPDATE');
v_process_old bool = (TG_OP = 'UPDATE' OR TG_OP = 'DELETE');
v_event text = TG_ARGV[0];
v_topic_template text = TG_ARGV[1];
v_attribute text = TG_ARGV[2];
v_record record;
v_sub text;
v_topic text;
v_i int = 0;
v_last_topic text;
begin
for v_i in 0..1 loop
if (v_i = 0) and v_process_new is true then
v_record = new;
elsif (v_i = 1) and v_process_old is true then
v_record = old;
else
continue;
end if;
if v_attribute is not null then
execute 'select $1.' || quote_ident(v_attribute)
using v_record
into v_sub;
end if;
if v_sub is not null then
v_topic = replace(v_topic_template, '$1', v_sub);
else
v_topic = v_topic_template;
end if;
if v_topic is distinct from v_last_topic then
-- This if statement prevents us from triggering the same notification twice
v_last_topic = v_topic;
perform pg_notify(v_topic, json_build_object(
'event', v_event,
'subject', v_sub,
'id', v_record.id
)::text);
end if;
end loop;
return v_record;
end;
$_$;

Hooking the database up to a GraphQL subscription can be achieved via CREATE TRIGGER:

之后即可通过 CREATE TRIGGER 将数据库变更与 GraphQL 订阅关联起来:

create trigger _500_gql_insert
after insert on messages
for each row
execute function tg__graphql_subscription(
'create', -- the "event" string, useful for the client to know what happened
'forum:$1:message', -- the "topic" the event will be published to, as a template
'forum_id' -- If specified, `$1` above will be replaced with NEW.forum_id or OLD.forum_id from the trigger.
);

Testing your subscription with Ruru使用 Ruru 测试订阅​

To test your subscription you will need to first subscribe and then trigger it.

测试订阅时,需要先发起订阅,然后再触发相应事件。

To subscribe, in one Ruru tab execute

首先,在一个 Ruru 标签页中执行以下查询以建立订阅:

subscription MySubscription {
forumMessage(forumId: 1) {
user
event
}
}

You should get the answer: "Waiting for subscription to yield data…"

此时应看到返回提示:"Waiting for subscription to yield data…"

To trigger the subscription, in another Ruru tab run a mutation that adds a message to that forum. This will depend on your implementation, for example:

接着,在另一个 Ruru 标签页中执行一个向该版块添加消息的 mutation 来触发订阅(具体字段视你的 schema 实现而定),例如:

mutation MyMutation {
createMessage(input: { message: { forumId: 1, body: "Hello World!" } }) {
clientMutationId
}
}

In this tab you will get the regular mutation answer. Going back to the previous tab, you will see the subscription payload. You are good to go! This should serve as the basis to implement your own custom subscriptions.

当前标签页会照常返回该 mutation 的执行结果;切回前一个标签页,就能看到刚刚推送过来的订阅 payload。至此大功告成!你可以此为基础,构建符合自己业务需求的自定义订阅。