Using PostGraphile as a Library作为库使用 PostGraphile
Library mode is the most popular way of running PostGraphile; it gives more power than using the CLI (see CLI usage) because you can leverage the capabilities and ecosystems of your chosen Node.js webserver (Express, Koa, Fastify, etc), but is more fully featured than Schema-only Usage.
库模式是运行 PostGraphile 最常用的方式:相比 CLI(见 CLI 用法),它能让你充分发挥所选 Node.js Web 服务器(Express、Koa、Fastify 等)的能力与生态,因而更加强大;同时又比纯 Schema 用法提供了更完整的功能支持。
PostGraphile instancePostGraphile 实例
Library mode is configured using a preset (see Configuration for
the options) and returns a PostGraphile instance pgl which has various
methods you can use depending on what you're trying to do.
库模式通过 preset 进行配置(具体选项见配置),并返回一个 PostGraphile 实例 pgl。你可以根据不同的使用场景调用该实例上的各种方法。
import preset from "./graphile.config.js";
import { postgraphile } from "postgraphile";
// Our PostGraphile instance:
export const pgl = postgraphile(preset);
pgl.createServ(grafserv)
Grafserv supports a number of different servers in the JS ecosystem, you
should import the grafserv function from the relevant grafserv subpath:
Grafserv 支持 JS 生态中的多种服务器框架,请从对应的 grafserv 子路径导入 grafserv 函数:
import { grafserv } from "postgraphile/grafserv/express/v4";
// OR: import { grafserv } from "postgraphile/grafserv/node";
// OR: import { grafserv } from "postgraphile/grafserv/koa/v2";
// OR: import { grafserv } from "postgraphile/grafserv/fastify/v4";
Then create your serv instance by passing this to the pgl.createServ()
method:
接着将其传给 pgl.createServ() 方法,创建你的 serv 实例:
const serv = pgl.createServ(grafserv);
This Grafserv instance (serv) can be mounted inside of your chosen server -
for instructions on how to do that, please see the relevant entry for your
server of choice in the Grafserv
documentation; typically there's a
serv.addTo(...) method you can use.
随后就可以将这个 Grafserv 实例(serv)挂载到你选用的服务器中——具体步骤请参阅 Grafserv 文档中对应服务器的章节;通常直接调用 serv.addTo(...) 方法即可。
Here's an example with Node's HTTP server:
以下是配合 Node 原生 HTTP 服务器的示例:
import { createServer } from "node:http";
import { grafserv } from "postgraphile/grafserv/node";
import { pgl } from "./pgl.js";
const serv = pgl.createServ(grafserv);
const server = createServer();
server.once("listening", () => {
server.on("error", (e) => void console.error(e));
});
serv.addTo(server).catch((e) => {
console.error(e);
process.exit(1);
});
server.listen(5678);
console.log("Server listening at http://localhost:5678");
And an example for Express:
以下是配合 Express 的示例:
import { createServer } from "node:http";
import express from "express";
import { grafserv } from "postgraphile/grafserv/express/v4";
import { pgl } from "./pgl.js";
const serv = pgl.createServ(grafserv);
const app = express();
const server = createServer(app);
server.once("listening", () => {
server.on("error", (e) => void console.error(e));
});
serv.addTo(app, server).catch((e) => {
console.error(e);
process.exit(1);
});
server.listen(5678);
console.log("Server listening at http://localhost:5678");
For information about using this serv instance with Connect, Express, Koa, Fastify,
Restify, or any other HTTP servers, please see the Grafserv
documentation.
若想了解如何将该 serv 实例集成到 Connect、Express、Koa、Fastify、Restify 或其他 HTTP 服务器中,请参阅 Grafserv 文档。
pgl.getSchemaResult()
Returns a promise to the schema result — an object containing:
返回一个解析为 schema 结果对象的 Promise,其中包含:
-
schema- the GraphQL schemaschema—— 生成的 GraphQL schema -
resolvedPreset- the resolved presetresolvedPreset—— 解析后的最终 preset
Note that this may change over time, e.g. in watch mode.
注意,该结果可能会随时间变化(例如在 watch 模式下)。
pgl.getSchema()
Shortcut to (await pgl.getSchemaResult()).schema — a promise to the GraphQL
schema the instance represents (may change due to watch mode).
(await pgl.getSchemaResult()).schema 的快捷方法,返回一个指向当前实例所代表 GraphQL schema 的 Promise(在 watch 模式下可能会发生变化)。
pgl.getResolvedPreset()
Get the current resolved preset that PostGraphile is using. Synchronous.
同步获取 PostGraphile 当前正在使用的已解析 preset。
pgl.release()
Call this when you don't need the PostGraphile instance any more and it will release any resources it holds (for example schema watching, etc).
当你不再需要该 PostGraphile 实例时调用此方法,它会释放所持有的所有资源(例如 schema 监听等)。
Example 1: single JS file, express示例 1:单文件 JS + Express
In this example we'll set up a PostGraphile server using ExpressJS all in a
single JS file that we can run directly with node.
在本示例中,我们将仅用单个 JS 文件基于 ExpressJS 搭建一个 PostGraphile 服务器,并直接通过 node 运行。
To start, create a directory for the project and initialize a Node.js project in that folder:
首先创建项目目录,并在其中初始化一个 Node.js 项目:
mkdir postgraphile_express
cd postgraphile_express
npm init -y
Installing dependencies安装依赖
Install the required packages:
安装所需的 npm 包:
- npm
- Yarn
- pnpm
- Bun
npm install --save express postgraphile
yarn add express postgraphile
pnpm add express postgraphile
bun add express postgraphile
Environment variables环境变量
It's bad practice to store credentials directly into source code, so instead we
use an environment variable DATABASE_URL to to store the database connection
string.
直接把数据库凭据硬编码进源码是糟糕的做法,因此我们使用环境变量 DATABASE_URL 来保存数据库连接字符串。
Additionally, we want PostGraphile to behave slightly differently in
development versus production: in development we want better error messages and
easier to read SQL; whereas, in production, we don't want to reveal more
information to potential attackers than we need to, and we want to execute as
fast as possible. Since we're in development, we'll use the
GRAPHILE_ENV=development envvar to indicate this.
此外,我们希望 PostGraphile 在开发环境与生产环境中表现出不同的行为:在开发环境下需要更友好的报错信息和更易读的 SQL;而在生产环境下则应避免向潜在攻击者暴露多余细节,并追求极致的执行速度。由于当前处于开发阶段,我们通过 GRAPHILE_ENV=development 环境变量来标识这一点。
To save us from having to pass the environment variables every time we run the server,
we can add them to a convenient .env file:
为了避免每次启动服务器都要手动传入环境变量,可以把它们写入 .env 文件中:
# Replace the contents of the square brackets with the details of your database
DATABASE_URL=postgres://[username]:[password]@[host]:[port]/[database]
GRAPHILE_ENV=development
Be sure to replace the square brackets with the relevant settings for your own database connection!
请务必将方括号中的占位内容替换为你自己的数据库连接配置!
Critically, we must ensure that this file is not tracked by git:
至关重要的是,必须确保该文件不会被 Git 追踪提交:
echo .env >> .gitignore
The code编写代码
Create a server.js file with the following contents:
新建 server.js 文件并填入以下内容:
import express from "express";
import { createServer } from "node:http";
import { postgraphile } from "postgraphile";
import { PostGraphileAmberPreset } from "postgraphile/presets/amber";
import { makePgService } from "postgraphile/adaptors/pg";
import { grafserv } from "postgraphile/grafserv/express/v4";
// Which port do we want to listen for requests on?
const PORT = 5678;
/** @type {GraphileConfig.Preset} */
const preset = {
extends: [PostGraphileAmberPreset],
pgServices: [
makePgService({
connectionString: process.env.DATABASE_URL,
schemas: ["public"],
}),
],
grafast: {
explain: true,
},
};
// Create our PostGraphile instance, `pgl`:
const pgl = postgraphile(preset);
// Create our PostGraphile grafserv instance, `serv`:
const serv = pgl.createServ(grafserv);
async function main() {
// Create an express app:
const app = express();
// Create a Node HTTP server, and have the express app handle requests:
const server = createServer(app);
// If the server were to produce any errors after it has been successfully
// set up, log them:
server.once("listening", () => {
server.on("error", (e) => void console.error(e));
});
// Mount our grafserv instance inside of the Express app, also passing the
// reference to the Node.js server for use with websockets (for GraphQL
// subscriptions):
await serv.addTo(app, server);
// Start listening for HTTP requests:
server.listen(PORT, () => {
console.log(`Server listening at http://localhost:${PORT}`);
});
}
// Start the main process, exiting if an error occurs during setup.
main().catch((e) => {
console.error(e);
process.exit(1);
});
The project is now complete, listing the project directory should show
至此项目文件已准备就绪,查看项目目录结构应如下所示:
postgraphile_express/
├── .env
├── .gitignore
├── node_modules/
├── package.json
├── package-lock.json
└── server.js
Configure your project by setting some options in package.json:
接下来在 package.json 中配置几个项目选项:
# Delete things we're not configuring right now
npm pkg delete author license description keywords scripts main
# Don't allow publishing to npm (`--json` since `true` is boolean not string)
npm pkg set private=true --json
# Use ESModule syntax and set our start script
npm pkg set type=module scripts.start="node server.js"
The package.json file should now have content similar to the following (with
the versions of express and postgraphile being the most recent):
此时 package.json 的内容应与下面类似(其中的 express 和 postgraphile 版本号为当前最新版本):
{
"name": "postgraphile_express",
"version": "1.0.0",
"dependencies": {
"express": "^4.21.2",
"postgraphile": "^5.0.0-beta.38"
},
"private": true,
"type": "module",
"scripts": {
"start": "node server.js"
}
}
To tidy up, let's make the following changes to the package.json file:
为了进一步规范配置,我们对 package.json 做如下调整:
{
"name": "postgraphile_express",
"version": "1.0.0",
- "main": "index.js",
+ "private": true,
+ "type": "module",
"scripts": {
+ "start": "node --env-file=./.env server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
- "keywords": [],
- "author": "",
- "license": "ISC",
- "description": "",
"dependencies": {
"express": "^4.21.2",
"postgraphile": "^5.0.0-rc.4"
}
}
The main things we've done here are:
这里主要完成了以下几项改动:
-
Remove the reference to a non-existant index.js file
移除指向不存在的
index.js文件的引用 -
Mark the project as "private" such that we can't attempt to
npm publishit to the npm repository将项目标记为“private”,防止意外执行
npm publish发布到 npm 仓库 -
Declare that
.jsfiles are ES modules, enabling the use ofimportstatements声明
.js文件采用 ES 模块格式,以支持import语法 -
Delete unnecessary metadata
删除多余的元数据字段
-
Add our
startscript, which runs the server contained inserver.jsusing thenodecommand, passing the environment variables stored in the.envfile添加
start脚本,通过node命令运行server.js中的服务,并加载.env文件中保存的环境变量
Running the server启动服务器
Thanks to the start script we added above, running our server is as simple as:
有了上面添加的 start 脚本,启动服务器只需运行:
npm start
Alternatively you can run the command from the start script directly:
或者也可以直接运行 start 脚本对应的命令:
node --env-file=./.env server.js
Either way, this will start a server at http://localhost:5678. Opening the
URL in a browser will show a user interface where a GraphQL query can be
entered. The following query is valid against any GraphQL schema and tells you
the fields that are available to be queried at the Query root:
无论哪种方式,都会在 http://localhost:5678 启动服务。在浏览器中打开该地址,即可看到用于输入 GraphQL 查询的交互界面。下面这段查询对任何 GraphQL schema 都有效,可以列出 Query 根类型下可供查询的所有字段:
query {
__schema {
queryType {
name
fields {
name
description
}
}
}
}
Example 2: TypeScript project, express示例 2:TypeScript 项目 + Express
To get the most out of PostGraphile (and the modern npm ecosystem in general), you'll want to be running TypeScript. This will give you much better auto-complete in your editor, type safety of your code, help with refactoring, and so much more.
想要充分发挥 PostGraphile(以及整个现代 npm 生态)的威力,强烈建议使用 TypeScript。它能为编辑器带来更精准的自动补全、完善的代码类型安全保障、更顺畅的重构体验等诸多好处。
This example will have three files in a src directory: graphile.config.ts,
pgl.ts and server.ts. It will also demonstrate including the
simple-inflection preset, included
as PgSimplifyInflectionPreset in graphile.config.ts
本示例将在 src 目录下创建三个文件:graphile.config.ts、pgl.ts 和 server.ts,并演示如何引入 simple-inflection preset(即在 graphile.config.ts 中配置 PgSimplifyInflectionPreset)。
Initialize the project初始化项目
To start, create a directory for the project and initialize a Node.js project in that folder:
首先创建项目目录,并在其中初始化一个 Node.js 项目:
mkdir postgraphile_express_typescript
cd postgraphile_express_typescript
npm init -y
Configure package.json to fit our project
按项目需求配置 package.json:
# Delete things we're not configuring right now
npm pkg delete version description main keywords author license scripts.test
# Don't allow publishing to npm (`--json` since `true` is boolean not string)
npm pkg set private=true --json
# Use ESModule syntax, never publish to npm, set some scripts
npm pkg set type=module scripts.start="node --env-file=./.env src/server.ts" scripts.build=tsc scripts.prod="node dist/server.js"
You should also ensure you're running Node v24+ (Node v22 is also supported,
but does not include built-in type stripping; you may need to pass
--experimental-strip-types to Node if using v22).
同时请确保运行环境为 Node v24+(虽然也支持 Node v22,但 v22 尚未默认开启内置类型擦除功能,使用时可能需要给 Node 传入 --experimental-strip-types 参数)。
# For nvm; other Node version managers exist.
echo 24 > .nvmrc
nvm use
Installing dependencies安装依赖
Install the required packages:
安装所需的 npm 包:
- npm
- Yarn
- pnpm
- Bun
npm install --legacy-peer-deps --save express postgraphile @graphile/simplify-inflection
npm install --save-dev typescript @tsconfig/node24 @tsconfig/node-ts @types/express @types/node
yarn add --legacy-peer-deps express postgraphile @graphile/simplify-inflection
yarn add --dev typescript @tsconfig/node24 @tsconfig/node-ts @types/express @types/node
pnpm add --legacy-peer-deps express postgraphile @graphile/simplify-inflection
pnpm add --save-dev typescript @tsconfig/node24 @tsconfig/node-ts @types/express @types/node
bun add --legacy-peer-deps express postgraphile @graphile/simplify-inflection
bun add --dev typescript @tsconfig/node24 @tsconfig/node-ts @types/express @types/node
Environment variables环境变量
As before, create a .env file containing your database connection string and
development/production environment setting:
与前文一样,创建一个 .env 文件,填入数据库连接字符串以及开发/生产环境标识:
DATABASE_URL=postgres://[username]:[password]@[host]:[port]/[database]
GRAPHILE_ENV=development
And ensure that it is not tracked by git:
并确保这些文件不会被 Git 追踪提交:
echo node_modules >> .gitignore
echo .env >> .gitignore
TypeScript configurationTypeScript 配置
Create a tsconfig.json file that extends from the relevant @tsconfig for your
Node.js major version (
e.g. if you're using Node v24.0.0 that would be
@tsconfig/node24),
and add also @tsconfig/node-ts if you want to use type
stripping; for example:
创建 tsconfig.json 文件,继承与你所用 Node.js 主版本对应的 @tsconfig 配置(例如使用 Node v24.0.0 时对应 @tsconfig/node24);如果需要使用类型擦除(type stripping)特性,还需一并继承 @tsconfig/node-ts,例如:
{
"extends": [
"@tsconfig/node24/tsconfig.json",
"@tsconfig/node-ts/tsconfig.json"
],
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist"
}
}
The code编写代码
In the postgraphile_express_typescript directory, create a src directory and
create three TypeScript files in the src folder: graphile.config.ts, pgl.ts
and server.ts with the contents shown below:
在 postgraphile_express_typescript 目录下新建 src 文件夹,并在其中创建 graphile.config.ts、pgl.ts 和 server.ts 三个 TypeScript 文件,内容分别如下所示:
src/graphile.config.ts
import { makePgService } from "postgraphile/adaptors/pg";
import { PostGraphileAmberPreset } from "postgraphile/presets/amber";
import { PgSimplifyInflectionPreset } from "@graphile/simplify-inflection";
const preset = {
extends: [PostGraphileAmberPreset, PgSimplifyInflectionPreset],
pgServices: [
makePgService({
connectionString: process.env.DATABASE_URL,
schemas: ["public"],
}),
],
grafast: {
explain: true,
},
grafserv: {
host: "localhost",
port: 5678,
},
} satisfies GraphileConfig.Preset;
export default preset;
src/pgl.ts
import { postgraphile } from "postgraphile";
import preset from "./graphile.config.ts";
export const pgl = postgraphile(preset);
.ts along with rewriteRelativeImportExtensions结合 rewriteRelativeImportExtensions 直接导入 .ts 文件With Node's new --experimental-strip-types flag (automatically enabled from
Node 24+), TypeScript syntax is removed so that the TS can be executed directly
as if it were JS. However, the files still need to be able to reference each
other. In the source code, that means referencing the .ts file; but when
TypeScript compiles the code for production the output will be .js files.
借助 Node 新增的 --experimental-strip-types 标志(自 Node 24+ 起默认启用),运行时会直接剥离 TypeScript 类型语法,让 TS 文件像普通 JS 一样直接执行。不过文件之间依然需要互相导入:在源码中导入路径写的是 .ts 后缀,但 TypeScript 编译生成生产代码后,产物却是 .js 文件。
Fortunately, TypeScript has added the configuration option
rewriteRelativeImportExtensions to ensure that you can use .ts to reference
TypeScript files in your source code whilst still ensuring that these imports
are output as .js when compiled for production usage.
好在 TypeScript 新增了 rewriteRelativeImportExtensions 编译选项:这样你在源码中可以用 .ts 后缀导入其他 TypeScript 文件,而在编译输出用于生产环境的产物时,这些导入路径会自动被改写为 .js。
src/server.ts
import { createServer } from "node:http";
import express from "express";
import { grafserv } from "postgraphile/grafserv/express/v4";
import preset from "./graphile.config.ts";
import { pgl } from "./pgl.ts";
const serv = pgl.createServ(grafserv);
const app = express();
const server = createServer(app);
server.once("listening", () => {
server.on("error", (e) => void console.error(e));
});
serv.addTo(app, server).catch((e) => {
console.error(e);
process.exit(1);
});
const { host, port } = preset.grafserv;
server.listen(port, host);
console.log(`Server listening at http://${host}:${port}`);
Contents of package.jsonpackage.json 内容参考
The package.json file should now have content similar to the following (likely
with different version numbers):
此时 package.json 文件内容应如下所示(具体版本号可能略有差异):
{
"name": "postgraphile_express_typescript",
"scripts": {
"start": "node --env-file=./.env src/server.ts",
"build": "tsc",
"prod": "node dist/server.js"
},
"type": "module",
"private": true,
"dependencies": {
"@graphile/simplify-inflection": "^8.0.0-rc.3",
"express": "^5.2.1",
"postgraphile": "^5.0.0-rc.4"
},
"devDependencies": {
"@tsconfig/node-ts": "^23.6.2",
"@tsconfig/node24": "^24.0.4",
"@types/express": "^5.0.6",
"@types/node": "^25.0.10",
"typescript": "^5.9.3"
}
}
Note that we have defined three scripts:
可以看到,这里定义了三个脚本:
-
startruns our source files directly using Node 24's type strippingstart利用 Node 24 的类型擦除能力直接运行源码文件 -
buildcompiles oursrc/*.tsfiles todist/*.jsfiles to run in productionbuild将src/*.ts编译为可供生产环境运行的dist/*.js文件 -
prodruns the compileddist/*.jsfiles in production, and expects the environment variables to already be set in the environment rather than reading them from a fileprod在生产环境中运行编译后的dist/*.js文件,此时假定环境变量已预先注入系统环境,不再从.env文件读取
Project Structure项目结构
The project structure should be
完整项目结构应如下所示:
postgraphile_express_typescript/
├── .env
├── .gitignore
├── .nvmrc
├── node_modules/
├── package.json
├── package-lock.json
├── src/
│ ├── graphile.config.ts
│ ├── pgl.ts
│ └── server.ts
└── tsconfig.json
Development开发环境运行
In development, run npm start as before. This will run the source code
directly using Node's native type stripping feature. This will start a server
at http://localhost:5678, opening the url in a browser will show a user
interface where a GraphQL query can be entered, for example
在开发阶段,和前面一样运行 npm start 即可,Node 会通过原生的类型擦除能力直接执行源码。服务同样会启动在 http://localhost:5678,在浏览器中打开该地址就会看到可输入 GraphQL 查询的界面,例如:
query {
__schema {
queryType {
name
fields {
name
description
}
}
}
}
npm start?运行 npm start 报错?If you get errors when running npm start it might be because you are not
running a sufficiently up to date version of Node.js, lacking the type stripping
features. If this is the case and you can't update to Node 24 for some reason,
you'll want to run TypeScript in watch mode (yarn tsc --watch) in one
terminal, and then execute the compiled JS code directly:
node --env-file=./.env dist/server.js.
如果运行 npm start 时遇到报错,很可能是当前 Node.js 版本过低、尚不支持类型擦除特性。若因某些原因暂时无法升级到 Node 24,可以在一个终端中开启 TypeScript 监听编译模式(yarn tsc --watch),再直接运行编译输出的 JS 文件:node --env-file=./.env dist/server.js。
Production生产环境部署
In production, we want to minimize overhead. To do so, we compile the
TypeScript to JavaScript up front by running the yarn build command. Then we
ship the resulting files (including the dist/ folder) to production and we
run the npm run prod command which executes the compiled code directly.
在生产环境中,我们希望尽量降低运行时开销。因此需要先运行 yarn build 将 TypeScript 预先编译为 JavaScript,再把产物文件(包括 dist/ 目录)部署到生产环境,并运行 npm run prod 直接执行编译后的代码。