pgSmartTags
Smart Tags enable you to customize how (or if) your PostgreSQL resources are represented in your PostGraphile GraphQL schema. Before reading this page, you should familiarize yourself with Smart Tags so that you know when and why you would use them.
Smart Tags 可以让你定制 PostgreSQL 中的各类 resource 是否暴露以及如何在 PostGraphile GraphQL schema 中呈现。阅读本页前,建议先熟悉 Smart Tags,了解何时以及为何要使用它们。
Recommended: TagsFilePlugin推荐方案:TagsFilePlugin
We recommend the postgraphile.tags.json5 file to most
users; you can enable it by adding the TagsFilePlugin to your preset:
对于大多数用户,我们推荐使用 postgraphile.tags.json5 文件;只需在 preset 中添加 TagsFilePlugin 即可启用:
import { TagsFilePlugin } from "postgraphile/utils";
export default {
// ...
plugins: [TagsFilePlugin],
};
The below plugin generators can be helpful if you have more advanced needs than can be served by this plugin.
如果该插件无法满足你的进阶需求,下面介绍的插件生成器可以派上用场。
Smart tags plugin generatorsSmart Tags 插件生成器
pgSmartTags and jsonPgSmartTags are plugin generators
that allows you to easily apply smart tags to various PostgreSQL entities.
pgSmartTags 和 jsonPgSmartTags 是两个插件生成器,便于你为各类 PostgreSQL 实体批量应用 smart tags。
-
pgSmartTagsFromFileis the highest level function, and loads smart tags from a JSON5 file.pgSmartTagsFromFile是封装层级最高的函数,用于从 JSON5 文件加载 smart tags。 -
jsonPgSmartTagsis likepgSmartTagsFromFile, except it allows you to specify the configuration object in code rather than via a JSON5 file.jsonPgSmartTags与pgSmartTagsFromFile类似,但允许你直接在代码中传入配置对象,而无需通过 JSON5 文件。 -
pgSmartTagsis the lowest level plugin, it allows you to apply smart tags to PostgreSQL entities that match your specified rules.pgSmartTags是最底层的插件生成器,支持根据你指定的规则为匹配的 PostgreSQL 实体应用 smart tags。
pgSmartTagsFromFilepgSmartTagsFromFile
Usage example:
使用示例:
import { PostGraphileAmberPreset } from "postgraphile/presets/amber";
import { pgSmartTagsFromFile } from "postgraphile/utils";
const SmartTagsPlugin = pgSmartTagsFromFile(
// JSON and JSONC are also JSON5 compatible, so you can use these extensions if you prefer:
"/path/to/my/tags.file.json5",
);
const preset: GraphileConfig.Preset = {
extends: [PostGraphileAmberPreset],
plugins: [
SmartTagsPlugin,
],
};
This plugin powers the postgraphile.tags.json5 file
enabled by TagsFilePlugin. You can use it multiple times to merge smart tags
from multiple files should you wish.
由 TagsFilePlugin 启用的 postgraphile.tags.json5 文件正是基于该插件实现的。如有需要,你也可以多次调用它以合并来自多个文件的 smart tags。
jsonPgSmartTagsjsonPgSmartTags
This plugin generator takes a JSONPgSmartTags object, and adds the relevant
tags to the relevant entities referenced. It is what powers
pgSmartTagsFromFile above, but you can also use it in your own
PostGraphile schema plugins.
该插件生成器接收一个 JSONPgSmartTags 对象,并将相应标签添加到所引用的数据库实体上。上文的 pgSmartTagsFromFile 底层正是基于它实现的,你也可以在自己的 PostGraphile schema 插件中直接调用它。
Importing引入方式
import { jsonPgSmartTags } from "postgraphile/utils";
Signature函数签名
function jsonPgSmartTags(
jsonOrThunk: ThunkOrDirect<PromiseOrDirect<JSONPgSmartTags | null>>,
subscribeToJSONUpdatesCallback?: SubscribeToJSONPgSmartTagsUpdatesCallback | null,
details?: { name?: string; description?: string; version?: string },
): GraphileConfig.Plugin;
type JSONPgSmartTags = {
version: 1;
config: {
[kind in PgSmartTagSupportedKinds]?: {
[identifier: string]: {
tags?: PgSmartTagTags;
description?: string;
attribute?: {
[attributeName: string]: {
tags?: PgSmartTagTags;
description?: string;
};
};
constraint?: {
[constraintName: string]: {
tags?: PgSmartTagTags;
description?: string;
};
};
};
};
};
};
type SubscribeToJSONPgSmartTagsUpdatesCallback = (
cb: UpdateJSONPgSmartTagsCallback | null,
) => void | Promise<void>;
Example示例
An example of an empty JSONPgSmartTags object would be:
一个空的 JSONPgSmartTags 对象示例如下:
{
version: 1,
config: {
class: {},
attribute: {},
constraint: {},
procedure: {},
},
}
A more in-depth example of this configuration file, with comments, is available in the postgraphile.tags.json5 file documentation.
关于此配置文件更详尽且带注释的示例,请参阅 postgraphile.tags.json5 文件文档。
Details详细说明
Within the config object, we can add entries for each supported “kind” of PostgreSQL entity. The supported entities include:
在配置对象中,我们可以为每种受支持的 PostgreSQL 实体“类别(kind)”添加条目。支持的实体包括:
-
class- for tables, views, materialized views, compound types and other table-like entities; things you'd find in thepg_classPostgreSQL system table.class—— 用于表、视图、物化视图、复合类型及其他类表实体,即可以在 PostgreSQLpg_class系统表中找到的对象。 -
attribute- for columns/attributes of aclass; things you'd find in thepg_attributePostgreSQL system table.attribute—— 用于class的列或属性,即可以在 PostgreSQLpg_attribute系统表中找到的对象。 -
constraint- for constraints; things you'd find in thepg_constraintPostgreSQL system table.constraint—— 用于各类约束,即可以在 PostgreSQLpg_constraint系统表中找到的对象。 -
procedure- for functions and procedures; things you'd find in thepg_procPostgreSQL system tableprocedure—— 用于函数和存储过程,即可以在 PostgreSQLpg_proc系统表中找到的对象
The value for each of these kinds would be another object, keyed by the identifier of the PostgreSQL entity, then containing the configuration for that entity type. Identifiers for each entity type differ:
每种类别对应的值都是一个映射对象:以 PostgreSQL 实体的标识符(identifier)为键,以该实体对应的配置为值。不同实体类型的标识符格式各不相同:
class-schema_name.table_nameattribute-schema_name.table_name.column_nameconstraint-schema_name.table_name.constraint_name-
procedure-schema_name.function_name(NOTE: since PostGraphile doesn't support function overloading, function parameters are not factored into the identifier.)procedure——schema_name.function_name(注意:由于 PostGraphile 不支持函数重载,函数参数不会计入标识符中。)
For each identifier, you may present the fully qualified form as shown above, or
you may drop the left most segments, e.g. a column id in table users in
schema app_public could be specified as app_public.users.id or users.id or
just id.
对于各类标识符,既可以采用上面展示的完整限定名,也可以省略左侧的层级前缀——例如 schema app_public 下 users 表中的 id 列,可以写成 app_public.users.id、users.id,或直接写成 id。
Where the form used is not fully qualified, the configuration will be applied to
all entities that match. For example if you wanted to omit create/update on all
created_at/updated_at columns across all your tables, the configuration
might look like:
当使用的不是完整限定名时,配置会应用到所有匹配的实体上。例如,如果你想在所有表上禁止创建和更新 created_at 与 updated_at 列,可以这样配置:
{
version: 1,
config: {
attribute: {
created_at: { tags: { omit: "create,update" } },
updated_at: { tags: { omit: "create,update" } },
},
},
}
The configuration object for each matched entity accepts the following parameters (all optional):
每个匹配实体的配置对象支持以下参数(均为可选):
-
tags- a map of all the tags you wish to apply; these will be merged with the tags applied through other means (overwriting tags of the same name). See the Smart Tags documentation for more information about what tags are available, and what values they can have.tags—— 包含要应用的所有标签的映射表;这些标签会与通过其他途径设置的标签合并(同名标签会被覆盖)。关于可用标签及合法取值的更多信息,请参阅 Smart Tags 文档。 -
description- a description to apply to this resource, equivalent to usingCOMMENT ONon the underlying PostgreSQL entity (except that Smart Comment parsing does not take place).description—— 为该 resource 添加描述信息,效果等同于在底层 PostgreSQL 实体上执行COMMENT ON(区别在于此处不会触发 smart comment 解析)。
For the class entity type, the following convenience attributes are also
available to enable you to keep tables, columns and constraints configured in
the same location. When used, the column/constraint identifiers must not be
fully qualified, since the table identifier will be automatically prepended for
you.
对于 class 实体类型,还提供了以下便捷属性,方便你将表、列和约束的配置集中写在同一处。使用这些属性时,列或约束的标识符切勿写成完整限定名,因为系统会自动将表标识符作为前缀拼接上去。
-
attribute- for columnsattribute—— 用于配置列 -
constraint- for constraintsconstraint—— 用于配置约束
To have this plugin work in watch mode, a subscribeToJSONUpdatesCallback
method can be passed as a second argument. If/when Graphile Build enters watch
mode, this callback will be called, and it will be passed a callback function
that in turn must be called when a change takes place. When watch mode is
exited, the function will be called again without a callback, and whatever was
in place for watching must be released. An example implementation of this can
be found in pgSmartTagsFromFile, which monitors a JSON5 file for
changes and triggers the schema to refresh when this file changes.
若要让该插件支持监听模式(watch mode),可以传入 subscribeToJSONUpdatesCallback 作为第二个参数。当 Graphile Build 进入监听模式时,系统会调用该方法并传入一个回调函数;每当配置发生变更时,你必须调用这个传入的回调函数来通知更新。退出监听模式时,系统会再次调用该方法但不传入回调参数,此时应释放之前建立的所有监听资源。pgSmartTagsFromFile 就是一个典型实现:它会监控 JSON5 文件的变化,并在文件改动时触发 schema 刷新。
pgSmartTagspgSmartTags
This is a more versatile, but higher effort plugin generator that powers
jsonPgSmartTags. Rather than passing a configuration object, a list
of rules (or a single rule) is passed.
pgSmartTags 是 jsonPgSmartTags 底层依赖的插件生成器,功能更加灵活强大,但也需要编写更多代码。它接收的不是静态配置对象,而是一组规则(或单条规则)。
Importing引入方式
import { pgSmartTags } from "postgraphile/utils";
Signature函数签名
function pgSmartTags(
initialRules: ThunkOrDirect<
PromiseOrDirect<PgSmartTagRule | PgSmartTagRule[] | null>
>,
subscribeToUpdatesCallback?: SubscribeToPgSmartTagUpdatesCallback | null,
details?: { name?: string; description?: string; version?: string },
): GraphileConfig.Plugin;
type PgSmartTagRule = {
serviceName?: string;
kind:
| "class"
| "attribute"
| "constraint"
| "procedure"
| "type"
| "namespace";
match: string | ((input: PgEntity) => boolean);
tags?: PgSmartTagTags;
description?: string;
};
type UpdatePgSmartTagRulesCallback = (
ruleOrRules: PgSmartTagRule | PgSmartTagRule[] | null,
) => void;
type SubscribeToPgSmartTagUpdatesCallback = (
cb: UpdatePgSmartTagRulesCallback | null,
) => PromiseOrDirect<void>;
Example示例
Hide every table in public schema except users:
隐藏 public schema 中除 users 以外的所有表:
import { pgSmartTags } from "postgraphile/utils";
const OnlyPublicUsersPlugin = pgSmartTags({
kind: "class",
match: (t) => t.getNamespace()?.nspname === "public" && t.relname !== "users",
tags: { behavior: "-*" },
});
export default {
// ...
plugins: [OnlyPublicUsersPlugin],
};
Details详细说明
Rules must specify a kind (class, attribute, constraint or procedure)
and a match which could be the identifier (following the same rules as for
jsonPgSmartTags) or a matcher function. The matcher function makes
this plugin generator incredibly powerful, for example it could be used to apply
tags to all PostgreSQL entities that match a particular criteria that does not
need to relate to the entity's name. The matcher function is passed
a pg-introspection entity, and must return a boolean to say whether this
entity should be matched or not.
每条规则都必须指定 kind(class、attribute、constraint 或 procedure)和 match 字段;其中 match 可以是标识符(匹配规则与 jsonPgSmartTags 相同),也可以是一个匹配器函数(matcher function)。正是匹配器函数让这个插件生成器拥有极高的灵活度——例如,你可以依据与实体名称无关的特定条件,为符合条件的所有 PostgreSQL 实体批量打上标签。匹配器函数会接收一个 pg-introspection 实体对象,并需要返回一个布尔值,指示该实体是否命中匹配条件。
Like with jsonPgSmartTags, the rule may also optionally supply the
tags Smart Tags object to be merged, and a description to overwrite the
previous description.
与 jsonPgSmartTags 相同,规则中还可以按需提供要合并的 tags Smart Tags 对象,以及用于覆盖原有描述的 description。
The plugin also supports a subscribeToUpdatesCallback to enable watch mode,
which works in the same way as subscribeToJSONUpdatesCallback from
jsonPgSmartTags.
该插件同样支持通过 subscribeToUpdatesCallback 启用监听模式,其工作方式与 jsonPgSmartTags 中的 subscribeToJSONUpdatesCallback 完全一致。