Skip to main content

Multiple GraphQL Schemas with PostGraphile在 PostGraphile 中使用多个 GraphQL Schema

Each PostGraphile instance only creates a single GraphQL schema — you don't get one schema per user based on permissions, for example. Typically, in GraphQL, a single schema is what you want — it allows you to use the various GraphQL tooling for autocomplete, linting, mapping, etc using the same shared schema.

每个 PostGraphile 实例只会创建一个 GraphQL schema——例如,它不会根据用户权限为每个用户单独生成一套 schema。在 GraphQL 中,通常你正需要单一的共享 schema,这样才能基于同一套 schema 使用各类 GraphQL 工具来完成自动补全、代码检查(linting)、类型映射等工作。

However it sometimes makes sense to provide two or more different schemas; for example if you have two completely independent use-cases, or if you need to generate a special "admin" schema that only admins can access.

不过,有时提供两个或多个不同的 schema 也很合理——例如你有两套完全独立的业务场景,或者需要生成一个仅限管理员访问的专属“管理端(admin)”schema。

Typically it's a good idea to put different schemas on different URIs; it makes it easier to point to the relevant schema, download its description, and perform the relevant linting/etc with it. If someone is not allowed access to a schema they simply cannot access that endpoint.

通常建议将不同的 schema 挂载到不同的 URI 上,这样更方便指向目标 schema、下载其描述文件并对其进行代码检查等操作。如果某位用户无权访问某个 schema,只需禁止其访问该端点即可。

It's possible to run multiple PostGraphile schemas in a single Node.js server, either mounting them at different endpoints or on the same URI and use a simple middleware to switch between them. The key thing is to not to build more PostGraphile instances then the number of services you have — do not build a PostGraphile instance per request! (This is because every time you create a PostGraphile instance, it will perform a fresh introspection of your database schema and generate the GraphQL API from that — this would cause considerable lag, and unnecessary load on your database!)

你可以在单个 Node.js 服务器中运行多个 PostGraphile schema,既可以分别挂载到不同端点,也可以共用同一个 URI 并通过简单的中间件在它们之间切换。关键在于,不要创建超出实际服务数量的 PostGraphile 实例——切勿为每个请求新建一次 PostGraphile 实例!(因为每次创建 PostGraphile 实例时,它都会重新对数据库 schema 执行一次内省(introspection),并据此生成 GraphQL API,这会带来显著延迟,并给数据库造成不必要的负载。)

Multiple endpoints多个端点​

Here's an example of mounting multiple PostGraphiles at different endpoints:

下面是将多个 PostGraphile 实例挂载到不同端点的示例:

import { createServer } from "node:http";
import express from "express";
import postgraphile from "postgraphile";
import { grafserv } from "postgraphile/grafserv/express/v4";
import userPreset from "./graphile.config.mjs";

// Create an express app
const app = express();
// (Add any Express middleware you want here.)

// Create a Node HTTP server, mounting Express into it
const server = createServer(app);
server.on("error", (e) => {
console.error(e);
});

// Definitions of the PostgreSQL service we wish to expose via separate
// GraphQL APIs:
const services = {
admin: "postgres:///admin",
user: "postgres:///user",
};

// Loop over the services, and add them to our Express app
for (const [service, connectionString] of Object.entries(services)) {
// Build a preset specifically for this service
const preset = {
extends: [userPreset],
pgServices: [makePgService({ connectionString })],
grafserv: {
graphqlPath: `/${service}/graphql`,
graphiqlPath: `/${service}`,
},
};
// Build a PostGraphile instance for this service
export const pgl = postgraphile(preset);
// Create the Grafserv instance for this PostGraphile instance using the Express adaptor
const serv = pgl.createServ(grafserv);
// Add the Grafserv instance's route handlers to the Express app, and register
// websockets if desired
await serv.addTo(app, server);
// TODO: check that enabling websockets on multiple grafservs via the same server doesn't cause any issues
}

// Start the Express server
server.listen(userPreset.grafserv?.port ?? 5678);

Single endpoint, multiple GraphQL schemas单端点,多个 GraphQL Schema​

It's also possible to switch which PostGraphile instance to use for a single endpoint based on some information provided in the HTTP request, but how you would do this is dependent on what webserver framework you're using.

你也可以在单个端点上根据 HTTP 请求携带的信息来切换要使用的 PostGraphile 实例,但具体实现方式取决于所用的 Web 服务器框架。

If you're using something simple like Node, Express or Connect then you can build middleware for each instance and then write a custom middleware to call the right one:

如果使用的是 Node 原生 HTTP、Express 或 Connect 等轻量框架,可以为每个实例分别构建中间件,再编写一个自定义中间件按需调用对应实例:

// TODO: this is untested!
import { createServer } from "node:http";
import express from "express";
import postgraphile from "postgraphile";
import { grafserv } from "postgraphile/grafserv/express/v4";
import userPreset from "./graphile.config.mjs";

// Create an express app
const app = express();
// (Add any Express middleware you want here.)

// Create a Node HTTP server, mounting Express into it
const server = createServer(app);
server.on("error", (e) => {
console.error(e);
});

// A preset shared between our services which disables websockets and
// subscriptions since they are not supported
const commonPreset = {
extends: [userPreset],
grafserv: { websockets: false },
disablePlugins: ["SubscriptionPlugin"],
};

// The services we wish to switch between
const services = {
admin: {
handler: express(),
pgl: postgraphile({
extends: [commonPreset],
pgServices: [makePgService({ connectionString: "postgres:///admin" })],
}),
},
user: {
handler: express(),
pgl: postgraphile({
extends: [commonPreset],
pgServices: [makePgService({ connectionString: "postgres:///user" })],
}),
},
};

// Mount the PostGraphile instances into the handlers
for (const { handler, pgl } of Object.values(services)) {
const serv = pgl.createServ(grafserv);
serv.addTo(handler);
}

// Add a custom middleware to switch between these handlers
app.use((req, res, next) => {
const isAdmin = req.user?.isAdmin;
if (isAdmin) {
services.admin.handler(req, res, next);
} else {
services.user.handler(req, res, next);
}
});

// Start the Express server
server.listen(userPreset.grafserv?.port ?? 5678);