Server Extensions
This page relates to changing how the PostGraphile HTTP server (Grafserv) and other non-schema concerns work. If you're instead looking to change the generated GraphQL schema (e.g. to add fields or types), see Schema Plugins.
本页介绍如何修改 PostGraphile HTTP 服务器(Grafserv)及其他非 schema 相关功能的工作方式。如果你想修改生成的 GraphQL schema(例如新增字段或类型),请参阅 Schema 插件。
In addition to the Graphile Build plugin system which builds the
GraphQL schema in PostGraphile, PostGraphile also has a plugin system for the
CLI and web layer. These use the same plugin system, graphile-config, just
different scopes.
除了用于构建 GraphQL schema 的 Graphile Build 插件系统之外,PostGraphile 还为 CLI 和 Web 层提供了插件系统。它们底层使用的都是同一套插件体系 graphile-config,只是作用域不同。
Server extensions are regular graphile-config plugins and presets. Add them to
your configuration in graphile.config.* and PostGraphile will load them
automatically when it loads your configuration file.
服务器扩展本质上就是标准的 graphile-config 插件和 preset。只需将它们添加到 graphile.config.* 配置文件中,PostGraphile 在加载配置时便会自动加载这些扩展。
Adding extensions添加扩展
You can typically install extensions with yarn add or npm install,
e.g.
通常可以通过 yarn add 或 npm install 安装扩展,例如:
yarn add @grafserv/persisted
but that's not enough to use them; you must also add them to your configuration,
either via plugins: [...] (for plugins) or extends: [...] (for presets).
If an extension makes available both plugins and a preset, it's likely that the
preset is what you want - typically it will compose those plugins together and
add a default set of options. Refer to the extension's documentation for the
correct instructions.
但仅仅安装包还不够,你还需要将其添加到配置中——插件通过 plugins: [...] 引入,preset 则通过 extends: [...] 引入。如果某个扩展同时导出了插件和 preset,通常优先使用 preset 即可,因为它一般已经组合好了相关插件并附带了合理的默认选项。具体用法请以对应扩展的文档为准。
Here's a basic graphile.config.ts with a server plugin:
下面是一个引入了服务器插件的基础 graphile.config.ts 示例:
import type { GraphileConfig } from "graphile-config";
import PersistedPlugin from "@grafserv/persisted";
const preset: GraphileConfig.Preset = {
plugins: [PersistedPlugin],
};
export default preset;
Writing your own plugins编写自定义插件
Server plugins are plain objects that implement graphile-config plugin
interfaces such as grafserv.middleware.*. Multiple plugins may register
middleware; the output of one middleware function is fed as input to the next.
Every plugin must have a unique name.
服务器插件就是实现了 graphile-config 插件接口(例如 grafserv.middleware.*)的普通对象。多个插件可以同时注册中间件,前一个中间件函数的输出会作为下一个中间件的输入。每个插件都必须拥有唯一的名称。
Here's a minimal plugin that does nothing:
下面是一个什么都不做的最简插件:
import type { GraphileConfig } from "graphile-config";
export const NoopPlugin: GraphileConfig.Plugin = {
name: "NoopPlugin",
};
Here's a plugin that hooks the Grafserv processGraphQLRequstBody
middleware, but doesn't actually make any changes:
下面是一个挂载了 Grafserv processGraphQLRequstBody 中间件、但实际未作任何修改的插件示例:
import type { GraphileConfig } from "graphile-config";
export const MyPlugin: GraphileConfig.Plugin = {
name: "MyPlugin",
version: "0.0.0",
grafserv: {
middleware: {
processGraphQLRequestBody(next, event) {
// mutate event.body as needed
return next();
},
},
},
};
Plugins are powerful. Depending on what you're trying to achieve, working with
the plugin system may require deep knowledge of the PostGraphile internals since
that is what you will be augmenting/overriding. It's hard to write documentation
to cover all possible use cases of the plugin system since it's incredibly
powerful, instead you may consider exploring existing plugins that achieve
similar functionality. Almost everything in PostGraphile is implemented through
the builtin set of plugins - use graphile config print plugins to see a list!
插件机制非常强大。由于插件实质上是在扩展或覆写 PostGraphile 的内部机制,实现特定需求时往往需要深入理解其内部原理。正因为插件系统功能极为灵活,文档很难涵盖所有应用场景,建议多参考实现类似功能的现有插件。事实上,PostGraphile 中的几乎所有功能都是通过内置插件实现的——运行 graphile config print plugins 即可查看完整列表!
Many things you might think you need a server plugin for are better served with standard HTTP middleware, e.g. by using Express/Koa/Fastify/etc middleware you can implement CORS, sessions, custom authentication flows, rate limiting, logging, routing, liveness/readiness/health endpoints, statistics collection and much more - you probably do not need to write PostGraphile server plugins for this kind of functionality.
很多你以为需要通过服务器插件实现的功能,其实更适合交给标准的 HTTP 中间件处理。例如,借助 Express、Koa、Fastify 等框架的中间件,你可以轻松实现 CORS、会话管理、自定义认证流程、限流、日志记录、路由分发、存活/就绪/健康检查接口以及统计采集等需求——这类场景通常无需编写 PostGraphile 服务器插件。
If you need help writing your own PostGraphile server plugins, ask in #help-and-support in our Discord chat.
如果你在编写 PostGraphile 服务器插件时需要帮助,欢迎前往我们的 Discord 社区 #help-and-support 频道提问。
Currently these scopes are undocumented, so here's some examples:
目前这些作用域尚未提供完整文档,下面先给出几个示例供参考:
Example: customizing Ruru's title示例:自定义 Ruru 页面标题
const title = "My Custom Ruru Title";
export const RuruTitlePlugin: GraphileConfig.Plugin = {
name: "RuruTitlePlugin",
version: "0.0.0",
grafserv: {
middleware: {
ruruHTML(next, event) {
const { htmlParts, request } = event;
htmlParts.titleTag = `<title>${escapeHTML(
title + " | " + request.getHeader("host"),
)}</title>`;
return next();
},
},
},
};
Example: manipulating the request body示例:修改请求体
Here's an example to allow users to pass only the operation name (not the full document) and have the server populate the document automatically.
下面这个示例允许客户端仅传入操作名称(而非完整的查询文档),由服务器自动填充对应的文档内容。
This is purely for demonstration of the plugin API, you should not use this
plugin! Instead, consider the @grafserv/persisted preset (which also uses
plugin.grafserv.middleware, but in a much less short-sighted way) and read up
on Trusted Documents.
此示例仅用于演示插件 API 的用法,请勿直接用于实际项目!若有此类需求,请改用 @grafserv/persisted preset(它同样基于 plugin.grafserv.middleware,但实现方式健壮得多),并进一步了解 Trusted Documents。
import { SafeError } from "grafast";
const documents = Object.assign(Object.create(null), {
QueryName: `query QueryName { __typename }`,
WhoAmI: `query WhoAmI { currentUser { name } }`,
CreatePost: `mutation CreatePost($input: CreatePostInput!) { createPost(input: $input) { post { id title } } }`,
});
export const QueryByNamePlugin: GraphileConfig.Plugin = {
name: "QueryByNamePlugin",
description:
"Only specify the query name and the query will be populated. EXAMPLE ONLY!",
version,
grafserv: {
middleware: {
processGraphQLRequestBody(next, event) {
const { body } = event;
const document = documents[body.operationName];
if (!document) {
throw new SafeError(
`QueryByNamePlugin couldn't find query '${body.operationName}'`,
{ statusCode: 400 },
);
} else {
body.query = document;
}
return next();
},
},
},
};