Skip to main content

Globally Unique Object Identification ("id" / "nodeId")全局唯一对象标识("id" / "nodeId")

The GraphQL Global Object Identification Specification is one of the best practices in GraphQL, it gives clients a way to uniquely identify each object in the schema and to fetch these objects by their IDs.

GraphQL 全局对象标识规范(Global Object Identification Specification)是 GraphQL 的最佳实践之一,它为客户端提供了一种在 schema 中唯一标识每个对象并通过 ID 获取该对象的方式。

By default, the postgraphile/presets/amber preset implements this specification. The amber preset assigns the unique identifier to every table with a primary key. The preset exposes the unique identifier as an attribute named id.

默认情况下,postgraphile/presets/amber preset 实现了该规范。Amber preset 会为每张带有主键的表分配全局唯一标识符,并将其暴露为名为 id 的属性。

It is common in database design to use the column name id for primary keys. For this reason, if there is an attribute named id that is already on the GraphQL type, the amber preset renames that attribute to rowId. If you want to use the amber preset but you do not like this behavior, you have several options:

在数据库设计中,主键列名通常也叫 id。因此,如果 GraphQL 类型上原本就存在名为 id 的属性,Amber preset 会将其重命名为 rowId。如果你想继续使用 Amber preset 但不喜欢这一 behavior,可以通过以下几种方式调整:

  1. You can use the postgraphile/presets/relay preset which makes several changes including removing rowId entirely.

    改用 postgraphile/presets/relay preset,它会引入多项调整,其中包括彻底移除 rowId。

  2. You can use a V4 preset that mimics the behavior and settings of PostGraphile V4 which used nodeId to represent the unique identifier.

    使用 V4 兼容 preset,沿用 PostGraphile V4 的 behavior 与设置,以 nodeId 作为全局唯一标识符。

  3. You can create your plugin similar to the following:

    编写类似下面的自定义插件:

const IdToNodeIdPlugin: GraphileConfig.Plugin = {
name: "IdToNodeIdPlugin",
version: "1.0.0",
inflection: {
replace: {
nodeIdFieldName() {
return "nodeId";
},
_attributeName(previous, options, details) {
const { codec, attributeName } = details;
const attribute = codec.attributes[attributeName];
const name = attribute.extensions?.tags?.name || attributeName;
return this.coerceToGraphQLName(name);
},
},
},
};

One common use case for the unique id field is as the cache key for your client library, e.g. with Apollo Client's dataIdFromObject:

全局唯一的 id 字段最常见的用途之一是作为客户端库的缓存键,例如搭配 Apollo Client 的 dataIdFromObject:

import ApolloClient from "apollo-client";
import { HttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";

const cache = new InMemoryCache({
dataIdFromObject: (object) => object.id || null,
// Or if you renamed 'id' to 'nodeId' then:
// dataIdFromObject: (object) => object.nodeId || null,
});

export const client = new ApolloClient({
link: new HttpLink(),
cache,
});

Using the Global Object Identifier in Function Arguments在函数参数中使用全局对象标识符​

The global object identifier can be accepted as a function argument using @argNvariant nodeId.

借助 @argNvariant nodeId,函数参数也可以直接接收全局对象标识符。

create table entity_a(
id uuid primary key
);

create table entity_b(
id uuid primary key
);

create table junction(
a_id uuid REFERENCES entity_a(id),
b_id uuid REFERENCES entity_b(id),
primary key (a_id, b_id)
);

create function add_junction_entry(a entity_a, b entity_b) returns junction as $$
insert into junction values (a.id, b.id) returning *;
$$ language sql volatile;

comment on function add_junction_entry(a entity_a, b entity_b) is $$
@arg0variant nodeId
@arg1variant nodeId
$$;

Disabling the Global Object Identifier禁用全局对象标识符​

The global object identifier is added by the amber preset. If you use the amber preset but you want to disable the global object identifier throughout your API, you can do so by disabling NodePlugin:

全局对象标识符是由 Amber preset 添加的。如果你使用 Amber preset 但希望在整个 API 中禁用全局对象标识符,可以通过禁用 NodePlugin 来实现:

graphile.config.mjs
export default {
// ...
disablePlugins: ["NodePlugin"],
};

Ensure that you have a good way of generating cache identifiers for your GraphQL client though!

不过请务必确保你的 GraphQL 客户端仍然有可靠的缓存标识符生成方案!

note注意

The GraphQL Global Object Identification Specification was previously known as the Relay Global Object Identification Specification, but it is not specific to Relay and is a general best practice for GraphQL APIs.

GraphQL 全局对象标识规范过去曾被称为“Relay 全局对象标识规范”,但它并不局限于 Relay,而是适用于所有 GraphQL API 的通用最佳实践。

More On the Relay Preset深入了解 Relay Preset​

If having both id: ID! and rowId: Int! in your schema bothers you (as it should!), you should consider using the postgraphile/presets/relay preset. This preset will hide raw primary keys from most of the schema, and will use global object identifiers instead — not just in the query schema but also in mutations and filtering (and, with a little guidance, in function inputs).

如果 schema 中同时出现 id: ID! 和 rowId: Int! 让你感到别扭(事实上确实该如此!),建议考虑使用 postgraphile/presets/relay preset。该 preset 会在 schema 的绝大部分位置隐藏原始主键,转而全面采用全局对象标识符——不仅用于查询 schema,也涵盖 mutation、过滤条件以及(稍加配置后的)函数入参。

graphile.config.mjs
import { PostGraphileAmberPreset } from "postgraphile/presets/amber";
import { PostGraphileRelayPreset } from "postgraphile/presets/relay";

export default {
extends: [
PostGraphileAmberPreset,
PostGraphileRelayPreset,
//...
],
// ...
};

Globally Unique ID Structure全局唯一 ID 的内部结构​

In GraphQL a globally unique ID should be treated as an "opaque" value: you should not extract values from inside it in your application. Though the globally unique ID is stable for the same object, when new objects are created there is no guarantee that their new ID will conform to the same encoding.

在 GraphQL 中,全局唯一 ID 应当被视为“不透明(opaque)”的值:应用层不应从其内部解析提取数据。虽然同一对象的全局唯一 ID 是稳定的,但无法保证后续新创建对象的 ID 仍采用完全相同的编码格式。

That said, it is generally easy to extract details from PostGraphile's globally unique IDs. Take for example the unique ID WyJQb3N0IiwxXQ==. By base64 decoding this value, we can see the data in it is ["Post",1]. This states that it is for the Post GraphQL type, and the associated primary key value is 1. (If you are using the V4 preset then nodeIds will use the table name (or a derivative thereof) rather than the GraphQL type name.)

尽管如此,从 PostGraphile 生成的全局唯一 ID 中解析出原始信息其实并不难。以 WyJQb3N0IiwxXQ== 为例,经 Base64 解码后内容为 ["Post",1],这表明它对应 GraphQL 类型 Post,关联的主键值为 1。(如果你使用的是 V4 preset,那么 nodeId 中包含的将是表名或其派生名称,而非 GraphQL 类型名。)

Thus, using globally unique IDs does not make your primary keys unobtainable, and doing so is not a goal of globally unique IDs. Should you need your primary keys to be meaningless, you should use an approach like UUIDv4 or a Feistel cipher.

因此,使用全局唯一 ID 并不能防止主键被外界获取,这也不是全局唯一 ID 的设计目标。如果你希望主键本身不暴露任何业务含义,应当采用 UUIDv4 或 Feistel 密码(Feistel cipher)等方案。

Decoding Node IDs解码 Node ID​

When you need to turn a Node ID back into the identifiers that your database expects, use the Grafast helper specFromNodeId(). Every GraphQL type that implements the Node interface registers a handler; you can retrieve it via build.getNodeIdHandler(typeName) inside extendSchema(). The mutation example shows this in context.

当你需要将 Node ID 还原为数据库所需的标识符时,可以使用 Grafast 提供的辅助函数 specFromNodeId()。每个实现了 Node 接口的 GraphQL 类型都会注册一个对应的处理器(handler),你可以在 extendSchema() 内部通过 build.getNodeIdHandler(typeName) 获取它。Mutation 示例展示了具体用法。

import { specFromNodeId } from "postgraphile/grafast";

const handler = build.getNodeIdHandler("Item");
const $nodeId = fieldArgs.getRaw(["input", "id"]);
const spec = specFromNodeId(handler, $nodeId);
const $item = build.pgResources.items.get(spec);

The specifier is often an object such as { id: Step<string> }, but the shape depends on the handler. Pass the specifier to the relevant resource or loader to continue working with the record.

返回的标识符描述对象(specifier)通常是类似 { id: Step<string> } 的对象,不过具体结构取决于对应的 handler。将该对象传给相应的 resource 或 loader,即可继续处理该记录。

const { organization_id: $organizationId, issue_id: $issueId } = specFromNodeId(
handler,
$nodeId,
);

更多细节请参阅 specFromNodeId 文档。

note注意

If the Node ID does not decode for the specified handler, the resulting steps resolve to null. Guard accordingly before continuing.

如果 Node ID 无法由指定的 handler 成功解码,生成的 step 将解析为 null,因此在继续后续逻辑前请做好空值判断。