Skip to main content

Exporting Your Schema导出 Schema

One of the major new features of PostGraphile V5 is the ability to export your schema as executable code. You might use this as a way to “eject” your schema so that you can take care of writing it yourself, or you could use it to make startup in production faster by removing the need for introspection and the plugin systems of graphile-build, or you might just use it to get a better understanding of how your schema works.

PostGraphile V5 的一项重要新特性,就是支持将 schema 导出为可执行代码。你可以借此“脱离(eject)”自动生成流程、亲自接管 schema 代码的编写;也可以通过省去启动时的数据库 introspection 和 graphile-build 插件加载来加快生产环境的冷启动速度;或者仅仅用它来更深入地理解自己 schema 的底层运作机制。

However you plan to use it, it’s a powerful and exciting new feature! To use this feature:

无论出于哪种目的,这都是一项既强大又令人振奋的新功能!使用方式只需两步:

  1. build your schema

    构建 schema

  2. call exportSchema on it

    对其调用 exportSchema

Just need SDL?只需要 SDL?

If you just want a GraphQL SDL file or an introspection JSON export, set preset.schema.exportSchemaSDLPath (and optionally preset.schema.exportSchemaIntrospectionResultPath) in your configuration. PostGraphile will refresh those files every time it rebuilds the schema.

如果你只是想要导出一份 GraphQL SDL 文件或 introspection JSON 结果,只需在配置中设置 preset.schema.exportSchemaSDLPath(以及可选的 preset.schema.exportSchemaIntrospectionResultPath)。此后每当 PostGraphile 重新构建 schema 时,都会自动更新这些文件。

Remember: the SDL does not have any implementation details, just a description of the type system. If you want to export an executable schema (with all the plan resolvers built in) then read on!

请注意:SDL 中不包含任何实现逻辑,仅仅是对类型系统的静态描述。如果你希望导出的是一个可执行 schema(内置所有 plan resolver),请继续往下看!

Here’s a simple example:

下面是一个简单的示例:

import { exportSchema } from "graphile-export";
import { postgraphile } from "postgraphile";
import config from "./graphile.config.js";
import * as jsonwebtoken from "jsonwebtoken";

const pgl = postgraphile(config);
async function main() {
const { schema, resolvedPreset } = await pgl.getSchemaResult();
const exportFileLocation = `${__dirname}/exported-schema.mjs`;
await exportSchema(schema, exportFileLocation, {
mode: "graphql-js",
// or:
// mode: "typeDefs",
modules: {
jsonwebtoken: jsonwebtoken,
},
});
}

main()
.finally(() => pgl.release())
.catch((e) => {
console.error(e);
process.exit(1);
});

Run this file, and you should see a exported-schema.mjs file containing your executable schema. You’ll notice that this schema does not import graphile-build, graphile-build-pg, etc — it just imports what it needs from graphql, grafast and similar runtime modules.

运行该文件后,你会看到生成了一个包含可执行 schema 的 exported-schema.mjs 文件。可以看到,这份文件并未引入 graphile-build、graphile-build-pg 等构建期模块——它仅从 graphql、grafast 等运行时模块导入真正需要的内容。

For a schema to be exported, all plugins must support exporting导出 schema 要求所有插件均支持导出

Not all PostGraphile plugins support exporting the schema, if you use plugins that don’t support exporting then your exported schema is likely to have runtime or even security issues. It is essential that you thoroughly test your exported schema before relying on it.

并非所有 PostGraphile 插件都支持 schema 导出。如果你使用的插件不支持导出,生成的 schema 很可能会出现运行时错误,甚至引发安全隐患。因此,在正式依赖导出的 schema 之前,务必对其进行充分测试。

Test your exported schema thoroughly务必充分测试导出的 schema

Exporting a GraphQL schema is error-prone, so you should test your exported schema thoroughly. The main failure mode for exported schemas is runtime errors or incorrect variable references when an exported function attempts to reference a variable in the parent scope and that variable wasn’t correctly handled via the EXPORTABLE() function from graphile-export. Using eslint-plugin-graphile-export will help catch most of these kinds of errors, but you should be careful to ensure that every function that will be exported is either wrapped with EXPORTABLE (with the correct args) or is from a declared module — see the graphile-export documentation.

导出 GraphQL schema 本身比较容易出错,因此必须对导出结果做全面测试。最常见的故障原因,是待导出的函数引用了父作用域中的变量,但该变量未能通过 graphile-export 提供的 EXPORTABLE() 函数正确处理,从而在导出后引发运行时报错或错误的变量引用。使用 eslint-plugin-graphile-export 可以帮你拦截绝大多数此类问题,但你仍需仔细确认每一个需要导出的函数要么已用 EXPORTABLE 正确包装(并传入正确的参数),要么来自已声明的模块——具体规则请参阅 graphile-export 文档。

TODO: update this warning, since this is less of an issue now that graphile-export does its own internal consistency checks.

TODO:需更新此警告,因为现在 graphile-export 已内置内部一致性检查,这类问题已经少得多。

Use your exported schema in dev and CI too在开发环境与 CI 中同样使用导出的 schema

If you will be exporting your GraphQL schema we highly recommend that you adopt the exported schema into every facet of your development lifecycle: you should use the exported schema in development, you should use it when running tests, and you should use it on your staging environments. This will give lots of opportunity for you and your QA engineer colleagues to catch any bugs in the export.

如果你计划导出 GraphQL schema,我们强烈建议在开发生命周期的各个环节都统一采用导出后的 schema:无论是本地开发、运行自动化测试,还是部署到预发布(staging)环境,都应直接使用它。这样能为你和 QA 工程师团队创造充足的机会,提前暴露并修复导出过程中可能存在的任何 Bug。

Consider using postgraphile/presets/minify for exported schemas考虑为导出的 schema 启用 postgraphile/presets/minify

When exporting your schema for use in a serverless environment, every byte matters - for bundling, for reading, and for executing. In these environments it's rare that introspection is a need (no GraphiQL or build tooling introspecting this endpoint), so this preset strips out all of the documentation and deprecations from the schema, and also attempts to remove other metadata from the code. The result is less code to export, smaller bundle size, and thereby a faster serverless startup time!

在将 schema 导出并部署到 Serverless 环境时,无论是打包、读取还是执行,每减少一个字节都意义重大。这类生产接口通常不需要 introspection(既不会挂载 GraphiQL,也不会有构建工具对它执行 introspection 查询),因此该 preset 会把 schema 中的所有描述文档与废弃声明(deprecation)剔除,并尝试移除代码中的其他元数据。最终效果就是导出代码更少、打包体积更小,从而显著加快 Serverless 环境的冷启动速度!

graphile.config.ts
import { PostGraphileAmberPreset } from "postgraphile/presets/amber";
import { PgMinifySchemaPreset } from "postgraphile/presets/minify";

const preset: GraphileConfig.Preset = {
extends: [PostGraphileAmberPreset, PgMinifySchemaPreset],
/* ... */
};

export default preset;

Because it removes descriptions and deprecation information, it is best suited to production exports where milliseconds matter (e.g. serverless) rather than traditional servers or developer-facing schemas. The preset is experimental, so expect these changes to evolve over time.

由于它会移除字段描述和废弃说明,因此更适合对启动耗时斤斤计较的生产环境导出(如 Serverless),而不建议用于传统常驻服务器或面向开发者的 schema。此外,该 preset 目前仍处于实验阶段,相关优化机制后续可能会有所调整。

Use eslint-plugin-graphile-export when writing plugins编写插件时建议配合使用 eslint-plugin-graphile-export

We highly recommend that plugin authors (both for internal project plugins and plugins distributed via npm) consult the graphile-export documentation in full. In particular, you should use the eslint-plugin-graphile-export rules to help ensure that the plan resolvers and similar that you add are themselves exportable. (This plugin is still experimental so we recommend that you only enable this ruleset on the files that contain PostGraphile plugins, and that you commit early and often so that any unintended changes to your codebase can be reverted.)

我们强烈建议所有插件作者(无论是项目内部自定义插件还是发布到 npm 的公共插件)完整阅读 graphile-export 文档。特别是建议启用 eslint-plugin-graphile-export 的规则集,以确保你新增的 plan resolver 等逻辑本身具备可导出性。(该 ESLint 插件目前仍处于实验阶段,因此建议仅对包含 PostGraphile 插件的文件启用这套规则,并保持高频提交代码,以便随时回滚对代码库造成的非预期修改。)

Run code validation against exported code对导出代码执行静态校验

You may get value from running ESLint, TypeScript, and/or other code validation tooling against the exported code to ensure there are no undefined variable references or similar.

针对导出后的代码运行 ESLint、TypeScript 等静态检查工具往往很有帮助,可以及时排查是否存在未定义的变量引用等问题。

Running the export运行导出的 schema​

run-exported.mjs
import { grafserv } from "postgraphile/grafserv/node";
import { createServer } from "node:http";
import preset from "./graphile.config.js";
import { schema } from "./exported-schema.mjs";

const server = createServer();
const serv = grafserv({ preset, schema });
serv.addTo(server);
server.listen(5555);
console.log("Listening on http://localhost:5555/");
Only import what you need!只导入必要的依赖!

You’ll notice that we import the node grafserv adaptor, our exported schema, and our preset, but no other PostGraphile-specific imports. The schema export itself will pull in a few other modules, but there should be no need to import postgraphile itself or the graphile-build system, since the schema has already built. This helps to keep runtime memory usage down, and importing less code should make for faster startup (and smaller bundles if you bundle your server, e.g. for serverless applications).

你会注意到,上面我们只导入了 node 的 Grafserv adaptor、导出的 schema 以及 preset,除此之外没有引入任何其他 PostGraphile 专属模块。导出的 schema 文件自身虽会按需引入少数几个依赖模块,但已经完全不需要加载 postgraphile 本体或 graphile-build 构建体系,因为 schema 早已被提前构建完毕。这不仅能显著降低运行时内存占用,减少模块导入量也能加快服务启动速度(如果在 Serverless 等场景下对服务端进行打包,还能有效减小最终产物体积)。