Skip to main content

Overview概览

What follows are some of the more commonly used options to serve as a quick reference, but this list can quickly become out of date (feel free to send a PR!). You can use TypeScript or the graphile config options command mentioned above to see what options are available to you — different presets and plugins make different options available.

下文列出了一些常用配置项供快速参考,但该列表可能随版本演进很快过时(欢迎随时提交 PR 补充!)。你可以通过 TypeScript 类型提示或上文提到的 graphile config options 命令来查看当前可用的配置项——不同的 preset 和插件会提供各自不同的选项。

inflection optionsinflection 选项​

(TypeScript type: GraphileBuild.InflectionOptions)

(TypeScript 类型:GraphileBuild.InflectionOptions)

None at this time.

暂无可配置项。

pgServices​

(TypeScript type: ReadonlyArray<GraphileConfig.PgServiceConfiguration>)

(TypeScript 类型:ReadonlyArray<GraphileConfig.PgServiceConfiguration>)

Details the PostgreSQL database(s) for PostGraphile to connect to; this is a separate option because it’s used in both the gather phase (for introspection) and at runtime.

用于指定 PostGraphile 要连接的 PostgreSQL 数据库。该配置之所以单独列出,是因为它在 gather 阶段(用于执行 introspection)以及运行时都会用到。

Generally it’s best to construct this by using the makePgService helper from the adaptor(s) you are using (see below), but if you want to know the nitty-gritty: each entry in the list is an object with the following keys (only name and adaptor are required):

通常建议通过所用适配器(adaptor)提供的 makePgService 辅助函数来构造此配置(见下文)。如果你想了解底层配置结构,列表中的每一项都是一个包含以下键的对象(其中仅 name 和 adaptor 为必填项):

  • name: string - an arbitrary unique name for this config; please keep it alphanumeric! Don’t set this unless you have more than one pgService; see warning below.

    name: string:该配置的自定义唯一名称,请仅使用字母和数字!除非你配置了多个 pgService,否则请勿设置此项;详见下文警告。

  • adaptor: PgAdaptor - the module to use as the postgres adaptor; e.g. the result of import("@dataplan/pg/adaptors/pg") for the pg module

    adaptor: PgAdaptor:用作 Postgres adaptor 的模块;例如使用 pg 模块时,可传入 import("@dataplan/pg/adaptors/pg") 的导出结果。

  • adaptorSettings - internal configuration object specific to the adaptor (automatically created by makePgService(), see adaptorSettings below)

    adaptorSettings:特定于该 adaptor 的内部配置对象(由 makePgService() 自动创建,详见下文 adaptorSettings)。

  • schemas: string[] - an array of PostgreSQL schema names to use

    schemas: string[]:要使用的 PostgreSQL schema 名称数组。

  • pgSettings: (requestContext: Grafast.RequestContext) => Record<string, string> | null - a callback function that will be called by the server to determine the pgSettings to use for a particular request

    pgSettings: (requestContext: Grafast.RequestContext) => Record<string, string> | null:一个回调函数,服务器会调用它来确定当前请求应使用的 pgSettings。

  • pgSettingsForIntrospection: Record<string, string> | null - the pgSettings to use when introspecting the database (for example if you want to change roles)

    pgSettingsForIntrospection: Record<string, string> | null:在对数据库执行 introspection 时使用的 pgSettings(例如用于切换数据库角色)。

  • pgSubscriber: PgSubscriber - a PgSubscriber instance that allows code to subscribe to LISTEN/NOTIFY events in the database - useful for GraphQL subscriptions, and also for schema watch mode.

    pgSubscriber: PgSubscriber:一个 PgSubscriber 实例,用于订阅数据库中的 LISTEN/NOTIFY 事件——在实现 GraphQL Subscription 以及 schema 的 watch 模式时会用到。

  • withPgClientKey: string - the key on the context object to store the withPgClient method the schema uses for communicating with the database. Defaults to withPgClient if name is "main" (the default), or ${name}_withPgClient otherwise.

    withPgClientKey: string:context 对象上用于存放 withPgClient 方法的键名(schema 通过该方法与数据库通信)。如果 name 为 "main"(默认值),则默认为 withPgClient;否则为 ${name}_withPgClient。

  • pgSettingsKey: string - the key on the context object to store the pgSettings configuration to use when communicating with the database. Defaults to pgSettings if name is "main" (the default), or ${name}_pgSettings otherwise.

    pgSettingsKey: string:context 对象上用于存放 pgSettings 配置的键名,与数据库通信时会读取该配置。如果 name 为 "main"(默认值),则默认为 pgSettings;否则为 ${name}_pgSettings。

  • pgSubscriberKey: string - the key on the context object to store the pgSubscriber instance to, for use during GraphQL subscriptions. Defaults to pgSubscriber if name is "main" (the default), or ${name}_pgSubscriber otherwise."

    pgSubscriberKey: string:context 对象上用于存放 pgSubscriber 实例的键名,供 GraphQL Subscription 期间使用。如果 name 为 "main"(默认值),则默认为 pgSubscriber;否则为 ${name}_pgSubscriber。

Example manual configuration (advanced, usually not needed)
import * as pg from "pg";
import * as adaptor from "@dataplan/pg/adaptors/pg";

const pgServices = [
{
name: "main",
schemas: ["app_public"],
pgSettingsKey: "pgSettings",
withPgClientKey: "withPgClient",
adaptor,
adaptorSettings: {
pool: new pg.Pool({ connectionString: process.env.DATABASE_URL }),
superuserPool: new pg.Pool({
connectionString: process.env.SUPERUSER_DATABASE_URL,
}),
},
},
];
info说明

The manual configuration approach above is advanced and usually not needed. Most users should use makePgService() as shown in the next example, which is simpler and handles the configuration for you.

上述手动配置方式属于高级用法,通常并不需要。大多数用户只需使用下个示例中的 makePgService(),它更简洁,且会自动为你完成相关配置。

Don’t set name unless you need to!除非确有需要,否则请勿设置 name!

We recommend that you don’t set a name unless you have more than one pgService. If you do, the different services may need different properties on context to detail how to connect, the settings to use, and how to subscribe to events. The withPgClientKey, pgSettingsKey and pgSubscriberKey options dictate under which keys these properties are stored on the context. By default, if the pgService’s name is left at its default ("main") then it uses "withPgClient", "pgSettings" and "pgSubscriber" respectively for these keys; otherwise it prefixes the keys with the name of the service and an underscore, for example a pgService with name: "otherdb" would use the context keys otherdb_withPgClient, otherdb_pgSettings and otherdb_pgSubscriber.

除非你配置了多个 pgService,否则建议不要设置 name。当你配置多个服务时,不同的服务可能需要在 context 上挂接各自的属性,以分别指定连接方式、使用配置以及事件订阅方式。withPgClientKey、pgSettingsKey 和 pgSubscriberKey 这三个选项决定了这些属性在 context 上的键名。默认情况下,如果 pgService 的 name 保持默认值("main"),这些键名会依次使用 "withPgClient"、"pgSettings" 和 "pgSubscriber";否则系统会在键名前加上服务名和下划线前缀——例如 name: "otherdb" 的 pgService 会使用 otherdb_withPgClient、otherdb_pgSettings 和 otherdb_pgSubscriber 作为 context 键名。

makePgService​

When PostGraphile (or, strictly, @dataplan/pg) wishes to communicate with PostgreSQL, it does so using an “adaptor”. The adaptor must expose a common set of functionality, but on top of that it can add adaptor-specific features, for example you might write an adaptor to add support for using your ORM of choice, so that in your custom fields/plan resolvers you can use that ORM to execute queries against the database.

当 PostGraphile(严格来说是 @dataplan/pg)需要与 PostgreSQL 通信时,会通过“适配器(adaptor)”实现。adaptor 必须对外暴露一组通用的基础能力,在此之上还可以添加特定于该 adaptor 的特性——例如,你可以编写一个 adaptor 来接入你常用的 ORM,从而在自定义字段或 plan resolver 中直接使用该 ORM 执行数据库查询。

Your choice of adaptor is quite important if you want to write custom JS logic in your schema, but otherwise it likely comes down to performance, convenience, and maybe avoiding additional dependencies. By default, PostGraphile uses the postgraphile/adaptors/pg adaptor which wraps the pg module.

如果你需要在 schema 中编写自定义 JS 逻辑,adaptor 的选择会非常关键;否则通常只需考量性能、便利性以及是否希望减少额外依赖即可。PostGraphile 默认使用 postgraphile/adaptors/pg adaptor,它封装了 pg 模块。

Every adaptor should expose a makePgService helper function that takes a common set of optional configuration parameters:

每个 adaptor 都应当暴露一个 makePgService 辅助函数,接收以下一组通用的可选配置参数:

  • connectionString
  • schemas
  • superuserConnectionString
  • pubsub (create a pgSubscriber entry; should default to true)

    pubsub(创建 pgSubscriber 实例;默认值应为 true)

  • pass-through options (a subset of those in pgServices above):

    透传选项(即上文 pgServices 选项的一个子集):

    • name (default: "main")

      name(默认值:"main")

    • pgSettings
    • pgSettingsKey (default with default name: pgSettings, otherwise: ${name}_pgSettings)

      pgSettingsKey(当 name 为默认值时,默认为 pgSettings;否则为 ${name}_pgSettings)

    • pgSettingsForIntrospection
    • withPgClientKey (default with default name: withPgClient, otherwise: ${name}_withPgClient)

      withPgClientKey(当 name 为默认值时,默认为 withPgClient;否则为 ${name}_withPgClient)

    • pgSubscriber
    • pgSubscriberKey (default with default name: pgSubscriber, otherwise: ${name}_pgSubscriber)

      pgSubscriberKey(当 name 为默认值时,默认为 pgSubscriber;否则为 ${name}_pgSubscriber)

The postgraphile/adaptors/pg adaptor additionally accepts these options:

此外,postgraphile/adaptors/pg adaptor 还额外接受以下选项:

  • pool - pass your own pre-built pg.Pool instance to use, in which case connectionString and poolConfig will be ignored. You are responsible for releasing this pool!

    pool:传入你预先创建的 pg.Pool 实例;此时 connectionString 和 poolConfig 将被忽略。请注意:你需自行负责释放该连接池!

  • poolConfig - additional configuration options (options other than connectionString) to pass through to pg.Pool; see the pg.Pool options which inherit the pg.Client options.

    poolConfig:除 connectionString 之外需透传给 pg.Pool 的额外配置项;参见 pg.Pool 选项(其配置继承自 pg.Client 选项)。

  • superuserPool - as pool, but for superuser connections (only used to install the watch fixtures in watch mode)

    superuserPool:与 pool 类似,但用于超级用户连接(仅用于在 watch 模式下安装 watch 监听组件)。

  • superuserPoolConfig - as poolConfig, but for superuser connections (only used to install the watch fixtures in watch mode)

    superuserPoolConfig:与 poolConfig 类似,但用于超级用户连接(仅用于在 watch 模式下安装 watch 监听组件)。

info说明

These common options are those that the postgraphile CLI might pass, which is why every adaptor should support them.

上述通用选项正是 postgraphile CLI 可能会传入的参数,因此每个 adaptor 都应当支持它们。

name must be unique!name 必须唯一!

The name option must be unique across all your pgServices; therefore if you have more than one entry in pgServices you must give each additional entry an explicit and unique name.

name 选项在所有 pgServices 配置中必须保持唯一;因此,如果 pgServices 中包含多个条目,必须为每个新增条目显式指定一个不重复的名称。

Each adaptor may additionally accept any other options it likes (but care should be taken to not conflict with options of other adaptors, or options that we might want to add to core in future).

每个 adaptor 也可以按需接收其他自定义选项(但应注意避免与其他 adaptor 的选项或未来可能添加到核心库的选项发生冲突)。

makePgService will return a fully resolved configuration object, suitable for inclusion into the pgServices array in your graphile.config.mjs (or similar) file.

makePgService 会返回一个解析完毕的完整配置对象,可直接放入 graphile.config.mjs(或类似配置文件)中的 pgServices 数组。

Example configuration via makePgService (recommended)
import { makePgService } from "postgraphile/adaptors/pg";

/** @type {GraphileConfig.Preset} */
const preset = {
// ...
pgServices: [
makePgService({
// Database connection string:
connectionString: process.env.DATABASE_URL,

// List of database schemas:
schemas: ["app_public"],

// Enable LISTEN/NOTIFY:
pubsub: true,

// Optional: additional pg.Pool configuration
poolConfig: {
max: 10,
idleTimeoutMillis: 30000,
},

// Optional, only needed for `--watch` mode:
superuserConnectionString: process.env.SUPERUSER_DATABASE_URL,

// Optional: additional superuser pg.Pool configuration
superuserPoolConfig: {
max: 2,
},
}),
],
};

adaptorSettings​

The adaptorSettings property is an internal configuration object that is created automatically when you use makePgService(). In general, you should not configure this directly. Instead, pass the configuration options directly to makePgService() as shown in the examples above.

adaptorSettings 属性是一个内部配置对象,在使用 makePgService() 时会自动生成。一般情况下,请勿直接配置此项,而是像上面的示例那样将配置选项直接传给 makePgService()。

If for some advanced reason you need to manually configure pgServices (rather than using makePgService()), then you would need to provide adaptorSettings with whatever the adaptor requires.

如果出于某些高级需求必须手动配置 pgServices(而非使用 makePgService()),则需要按相应 adaptor 的要求提供 adaptorSettings。

postgraphile/adaptors/pg​

(Or, equivalently, postgraphile/@dataplan/pg/adaptors/pg or @dataplan/pg/adaptors/pg)

(或等价路径:postgraphile/@dataplan/pg/adaptors/pg 或 @dataplan/pg/adaptors/pg)

This adaptor uses the pg module under the hood and uses the pg.Pool API primarily, it accepts the following options:

该 adaptor 底层使用 pg 模块并主要调用 pg.Pool API,支持以下配置项:

  • pool - pass your own pre-built pg.Pool instance to use, in which case all other (non-superuser) options will be ignored. You are responsible for releasing this pool!

    pool:传入你预先创建的 pg.Pool 实例;此时所有其他(非超级用户)选项都将被忽略。请注意:你需自行负责释放该连接池!

  • connectionString - the database connection string to use, we’ll create a pool for you automatically (and handle releasing it) using this connection string

    connectionString:要使用的数据库连接字符串;系统会基于该连接字符串为你自动创建连接池(并负责后续释放)。

  • poolConfig - additional configuration options (options other than connectionString) to pass through to pg.Pool; see the pg.Pool options which inherit the pg.Client options.

    poolConfig:除 connectionString 之外需透传给 pg.Pool 的额外配置项;参见 pg.Pool 选项(其配置继承自 pg.Client 选项)。

  • pubsub (default: true) - enable LISTEN/NOTIFY via creation of a pgSubscriber

    pubsub(默认值:true):通过创建 pgSubscriber 启用 LISTEN/NOTIFY。

  • superuserPool - as pool, but for superuser connections (only used to install the watch fixtures in watch mode)

    superuserPool:与 pool 类似,但用于超级用户连接(仅用于在 watch 模式下安装 watch 监听组件)。

  • superuserConnectionString - as connectionString, but for superuser connections (only used to install the watch fixtures in watch mode)

    superuserConnectionString:与 connectionString 类似,但用于超级用户连接(仅用于在 watch 模式下安装 watch 监听组件)。

  • superuserPoolConfig - as poolConfig, but for superuser connections (only used to install the watch fixtures in watch mode)

    superuserPoolConfig:与 poolConfig 类似,但用于超级用户连接(仅用于在 watch 模式下安装 watch 监听组件)。

Note if pool is provided then connectionString and poolConfig should not be specified. Similarly if superuserPool is provided then superuserConnectionString and superuserPoolConfig should not be specified.

注意:如果提供了 pool,则不应再指定 connectionString 和 poolConfig。同理,如果提供了 superuserPool,则不应再指定 superuserConnectionString 和 superuserPoolConfig。

gather optionsgather 选项​

(TypeScript type: GraphileBuild.GatherOptions)

(TypeScript 类型:GraphileBuild.GatherOptions)

  • pgStrictFunctions: boolean - if true, we’ll treat all PostgreSQL function arguments that don’t have defaults as being required (non-nullable)

    pgStrictFunctions: boolean:如果为 true,所有未设置默认值的 PostgreSQL 函数参数都将被视为必填(非空)。

  • pgJwtTypes: string | string[] - an array of (or comma separated list of) the names (including schemas) for the types in the database to convert into a JWT (equivalent to giving these type the behavior "-table +jwt"); example: pgJwtTypes: "app_public.jwt_token"

    pgJwtTypes: string | string[]:指定数据库中要转换为 JWT 的类型名称(需包含所属 schema)的数组或逗号分隔列表(效果等同于为这些类型赋予 "-table +jwt" behavior);示例:pgJwtTypes: "app_public.jwt_token"。

  • installWatchFixtures: boolean - if not false and schema is in watch mode then we will attempt to install the “event triggers” into the database so that PostGraphile can be notified when your database changes

    installWatchFixtures: boolean:如果未设为 false 且 schema 处于 watch 模式,系统将尝试在数据库中安装“事件触发器(event triggers)”,以便在数据库发生变更时通知 PostGraphile。

Deprecated options:

已弃用的选项:

  • pgV4UseTableNameForNodeIdentifier: boolean - if true, uses the table name instead of the type name in the Node identifier (highly discouraged because it significantly increases the risk of NodeID conflicts)

    pgV4UseTableNameForNodeIdentifier: boolean:如果为 true,则在 Node 标识符中使用表名而非类型名(强烈不推荐,因为这会显著增加 Node ID 冲突的风险)。

schema optionsschema 选项​

(TypeScript type: GraphileBuild.SchemaOptions)

(TypeScript 类型:GraphileBuild.SchemaOptions)

tip提示

Plugins may add additional options, please refer to your plugins’ documentation to determine the options that they offer.

插件可能会新增更多选项,具体支持的选项请查阅对应插件的文档。

  • defaultBehavior: string | undefined - if set, applies a default behavior to all entities; for example to prefer lists over connections: +list -connection.

    defaultBehavior: string | undefined:若设置此项,会为所有实体应用默认的 behavior;例如想优先使用列表而非 Connection,可设为 +list -connection。

  • dontSwallowErrors: boolean - if true, errors during the schema build process will throw rather than the system trying to recover from them. Recommended, but not enabled by default as it can be a barrier to entry to new users.

    dontSwallowErrors: boolean:如果为 true,schema 构建过程中发生错误时会直接抛出异常,而不会尝试容错恢复。建议开启,但由于可能抬高新手的上手门槛,默认未启用。

  • exportSchemaSDLPath: string | undefined - when set, writes the latest GraphQL schema definition (SDL) to the given path every time the schema is rebuilt.

    exportSchemaSDLPath: string | undefined:设置后,每次重新构建 schema 时都会将最新的 GraphQL schema 定义(SDL)写入指定路径。

  • exportSchemaIntrospectionResultPath: string | undefined - when set, writes the GraphQL introspection JSON to the given path alongside SDL exports.

    exportSchemaIntrospectionResultPath: string | undefined:设置后,在导出 SDL 的同时也会将 GraphQL introspection JSON 写入指定路径。

  • jsonScalarAsString: boolean - if true, JSON values will be stringified rather than returned as “dynamic” objects.

    jsonScalarAsString: boolean:如果为 true,JSON 值将以字符串形式返回,而非作为“动态”对象返回。

  • pgForbidSetofFunctionsToReturnNull: boolean - if true, setof functions cannot return null, so our list and connection types can be non-nullable in more places.

    pgForbidSetofFunctionsToReturnNull: boolean:如果为 true,则禁止返回集合的函数(setof 函数)返回 null,从而让列表类型和 Connection 类型在更多位置上可以声明为非空。

  • pgJwtSecret
  • pgJwtSignOptions
  • pgOrderByNullsLast: boolean | undefined - if true, orders such that nulls are always last; if false, orders such that nulls are always first; otherwise uses the default ordering

    pgOrderByNullsLast: boolean | undefined:如果为 true,排序时始终将 null 值排在最后;如果为 false,则始终将 null 值排在最前;未设置时使用默认排序规则。

  • pgUseCustomNetworkScalars: boolean - if not false, adds the CidrAddress, MacAddress and similar types for PostgreSQL network scalars.

    pgUseCustomNetworkScalars: boolean:如果未设为 false,则会为 PostgreSQL 网络标量类型添加 CidrAddress、MacAddress 等对应类型。

  • sortExport: boolean - if true (default: false), sorts exported SDL and introspection output for stable diffs.

    sortExport: boolean:如果为 true(默认值:false),会对导出的 SDL 和 introspection 结果进行排序,以保证 diff 结果稳定。

grafast optionsgrafast 选项​

(TypeScript type: GraphileConfig.GrafastOptions)

(TypeScript 类型:GraphileConfig.GrafastOptions)

  • explain - a list of ‘explain’ types that should be exposed to clients via extensions.explain (plan for the operation plan, sql for the SQL), or true to expose everything.

    explain:指定通过 extensions.explain 向客户端暴露哪些 “explain” 类型(plan 表示操作执行计划,sql 表示执行的 SQL),或设为 true 以暴露全部信息。

  • context - an object (or function that returns an object, or promise to an object) to be merged into the GraphQL context, accessible from plan resolvers. If a function, it will receive two parameters, first is the request context (which may contain details such as the incoming HTTP request, depends on what server/etc you are using) and the second is the current context object that your results will be merged into (overwriting pre-existing keys).

    context:一个对象(或返回对象的函数,或返回对象 Promise 的异步函数),其内容会被合并到 GraphQL context 中,供 plan resolver 访问。如果是函数,它会接收两个参数:第一个是请求上下文(可能包含传入的 HTTP 请求等详情,具体取决于所使用的服务端框架等),第二个是当前的 context 对象;你的返回值会被合并到该对象中(并覆盖已有同名键)。

grafserv optionsgrafserv 选项​

(TypeScript type: GraphileConfig.GrafservOptions)

(TypeScript 类型:GraphileConfig.GrafservOptions)

  • port: number - Port number to listen on (default: 5678)

    port: number:监听的端口号(默认值:5678)。

  • host: string - Host to listen on (default: ‘127.0.0.1’; consider setting to ‘0.0.0.0’ in Docker and similar environments)

    host: string:监听的主机地址(默认值:‘127.0.0.1’;在 Docker 等类似环境中建议设为 ‘0.0.0.0’)。

  • graphqlPath: string - The path at which GraphQL will be available; usually /graphql

    graphqlPath: string:提供 GraphQL 服务的路径;通常为 /graphql。

  • graphiqlPath: string - The path at which GraphiQL will be available; usually /

    graphiqlPath: string:提供 GraphiQL 界面的路径;通常为 /。

  • eventStreamPath: string - The path at which the GraphQL event stream would be made available; usually /graphql/stream

    eventStreamPath: string:提供 GraphQL 事件流的路径;通常为 /graphql/stream。

  • graphqlOverGET: boolean - If true, we’ll support GraphQL queries over the GET method (beware of the security implications, for example cross-site timing attacks)

    graphqlOverGET: boolean:如果为 true,将支持通过 GET 方法发起 GraphQL 查询(请注意由此带来的安全隐患,例如跨站时序攻击)。

  • graphiql: boolean
  • graphiqlOnGraphQLGET: boolean - If true, then we will render GraphiQL on GET requests to the /graphql endpoint

    graphiqlOnGraphQLGET: boolean:如果为 true,当对 /graphql 端点发起 GET 请求时,将渲染 GraphiQL 界面。

  • watch: boolean - Set true to enable watch mode

    watch: boolean:设为 true 以开启 watch 模式。

  • maxRequestLength: number - The length, in bytes, for the largest request body that the server will accept, only used if the framework of choice doesn’t already handle input parsing

    maxRequestLength: number:服务器可接受的最大请求体字节数,仅在所选框架本身未处理请求体解析时生效。

pgSettings​

Connections from PostGraphile to the PostgreSQL database may need to carry with them custom settings to be set within the PostgreSQL transaction. These can be used to indicate simple PostgreSQL settings such as statement_timeout=5000, or can be used to indicate details of the currently active user (e.g. jwt.claims.user_id = 42).

PostGraphile 与 PostgreSQL 数据库建立连接时,可能需要在 PostgreSQL 事务中携带自定义会话设置。这类设置既可用于配置基础的 PostgreSQL 参数(如 statement_timeout=5000),也可用于传递当前活跃用户的详细信息(例如 jwt.claims.user_id = 42)。

Every pgService can indicate its own pgSettings callback to dictate which settings that specific service should use with its associated database (see pgServices above), and these settings are added to the GraphQL context using the key set in that services’ pgSettingsKey.

每个 pgService 都可以指定自己的 pgSettings 回调,用来决定该服务对其关联数据库使用的会话设置(参见上文 pgServices),这些设置会以对应服务的 pgSettingsKey 为键名添加到 GraphQL context 中。

Presets may also add values to pgSettings, for example postgraphile/presets/lazy-jwt parses the Authorization header and adds the claims from the JWT to pgSettings.

preset 也可能向 pgSettings 中写入值,例如 postgraphile/presets/lazy-jwt 会解析 Authorization 请求头,并将 JWT 中的 claims 写入 pgSettings。

lazy-jwt is intentionally minimallazy-jwt 仅提供极简实现

postgraphile/presets/lazy-jwt is a stopgap for teams that are still wiring up their own authentication. It only supports Bearer tokens, expects a shared secret unless you override the verification options, and cannot help with common production concerns such as refresh tokens, revocation, or key rotation. Plan to replace it with middleware in your application framework that verifies credentials and then share that information with PostgreSQL through pgSettings.

postgraphile/presets/lazy-jwt 只是为尚未接好自有认证系统的团队提供的权宜之计。它仅支持 Bearer token,除非覆盖校验选项否则默认依赖共享密钥,且无法满足刷新令牌、令牌吊销或密钥轮换等常见生产级需求。建议后续将其替换为应用框架中的中间件:在中间件里完成凭证校验,再通过 pgSettings 将认证信息传递给 PostgreSQL。

For most PostGraphile users there’s only one pgService, and the default pgSettingsKey is "pgSettings", so rather than configuring pgSettings via the adaptor you might opt to configure it via including a pgSettings key in the object you return from the Grafast context callback mentioned in the “Grafast options” section above. The value for this key should be a POJO (plain old JavaScript object) with string keys and string values, and you should be careful to copy across settings from the pgService adaptor and any presets/plugins that may have added to it. For example:

对大多数 PostGraphile 用户而言,通常只有一个 pgService,且默认的 pgSettingsKey 为 "pgSettings"。因此除了通过 adaptor 配置外,你也可以在上文“Grafast 选项”一节提到的 Grafast context 回调所返回的对象中直接包含 pgSettings 键。该键的值应为一个键和值均为字符串的普通 JavaScript 对象(POJO),并注意保留和合入 pgService adaptor 以及各类 preset/插件可能已添加的设置。例如:

graphile.config.mjs
export default {
// ...

grafast: {
context(requestContext, args) {
return {
pgSettings: {
// If any pgSettings were already set, mix them in
...args.contextValue?.pgSettings,
// Add our own settings
statement_timeout: "10000",
},
};
},
},
};
Naming conventions命名规范

You can use pgSettings to define variables that your Postgres functions/policies depend on, or to tweak internal Postgres settings.

你可以使用 pgSettings 来定义 Postgres 函数或策略(policy)所依赖的变量,或用于调整 Postgres 内部配置。

When adding variables for your own usage, the keys must contain either one or two period (.) characters, and the prefix (the bit before the first period) must not be used by any Postgres extension. We recommend using a prefix such as jwt. or myapp.. Examples: jwt.claims.userid, myapp.is_admin

添加自定义变量时,键名必须包含一个或两个英文句点(.),且前缀(第一个句点前的部分)不能被任何 Postgres 扩展占用。建议使用 jwt. 或 myapp. 之类的前缀,例如 jwt.claims.userid、myapp.is_admin。

Variables without periods will be interpreted as internal Postgres settings, such as role, and will be applied by Postgres.

不包含句点的变量名会被解释为 Postgres 内部设置(如 role),并由 Postgres 直接应用。

Exposing HTTP request data to PostgreSQL向 PostgreSQL 传递 HTTP 请求数据​

Using the pgSettings functionality mentioned above you can extend the data made available within PostgreSQL through current_setting(...). Remember: the grafast.context entry can be a callback (even an asynchronous callback if you need) which can extract details from the HTTP request.

利用上文介绍的 pgSettings 功能,你可以扩展在 PostgreSQL 中通过 current_setting(...) 读取的数据。别忘了:grafast.context 可以是一个回调函数(如有需要甚至可以是异步函数),从而可以从 HTTP 请求中提取相关信息。

When using PostGraphile in library mode, you will likely have a middleware that handles user authentication (whether this be via sessions, cookies, or JWTs). You can use the requestContext to extract details from the request that came through your Grafserv adaptor and then expose this data to PostgreSQL; for example in an express app you might do something like:

以库模式(library mode)使用 PostGraphile 时,你通常已经有负责用户认证的中间件(无论是基于 session、cookie 还是 JWT)。你可以利用 requestContext 从 Grafserv adaptor 接收的请求中提取信息,再将这些数据传递给 PostgreSQL;例如在 Express 应用中,可以这样写:

graphile.config.js
export default {
// ...

grafast: {
async context(requestContext, args) {
// Extract request details from the requestContext:
const req = requestContext.expressv4?.req;

return {
pgSettings: {
...args.contextValue?.pgSettings,
// Expose a specific header (if present) to PostgreSQL
"myapp.headers.x_something": req?.getHeader("x-something"),
// Expose the user id from the request, if present
"myapp.user_id": req?.user?.id,
},
};
},
},
};

If you’re using the PostGraphile CLI then you won’t have middleware to do the heavy lifting for you, but you can still process incoming request headers - this more complicated example extracts the user’s ID from a JWT and sends that and the value of a specific HTTP header to PostgreSQL:

如果你使用的是 PostGraphile CLI,虽然没有中间件帮你完成这些繁重工作,但依然可以自行处理传入的请求头——下面这个稍复杂的示例展示了如何从 JWT 中提取用户 ID,并将其与特定 HTTP 请求头的值一同发送给 PostgreSQL:

graphile.config.js
import jwt from "jsonwebtoken";

const JWT_SECRET = process.env.JWT_SECRET;

export default {
// ...

grafast: {
async context(requestContext, args) {
// Extract request details from the requestContext:
const req = requestContext.node?.req;
// Or: const req = requestContext.expressv4?.req;
// Or: const ctx = requestContext.koav2?.ctx;
// Or: const req = requestContext.fastifyv4?.request;

const context = {
// Base settings for all requests:
pgSettings: {
...args.contextValue?.pgSettings,
// Expose a specific header (if present) to PostgreSQL
"myapp.headers.x_something": req?.getHeader("x-something"),
},
};

// Process the authorization header, if present
const auth = req?.headers["authorization"];
if (typeof auth === "string" && typeof JWT_SECRET === "string") {
const parts = auth.split(" ");
if (parts.length === 2 && parts[0].toLowerCase() === "bearer") {
const token = parts[1];
const claims = jwt.verify(token, JWT_SECRET, {
algorithms: ["HS256", "HS384"],
audience: "postgraphile",
complete: false,
});
// Expose the user id from the request, if present
context.pgSettings["myapp.user_id"] = claims.uid;
}
}

return context;
},
},
};
Use abstractions使用抽象层

GraphQL itself is transport agnostic, as is grafast, so depending on how you choose to use your PostGraphile schema you may or may not have access to an HTTP request. Your context callback should be written to support all the different ways that your schema may be used: directly, over HTTP, using websockets, etc.

GraphQL 本身与传输协议无关,grafast 亦是如此;因此根据你使用 PostGraphile schema 的方式不同,执行时未必能获取到 HTTP 请求对象。编写 context 回调时,应当兼顾 schema 可能被使用的各种方式:直接调用、通过 HTTP 请求、通过 WebSocket 等。

Do not expose the request, response or requestContext objects via the GraphQL context, always use abstractions.

切勿通过 GraphQL context 直接暴露 request、response 或 requestContext 对象,请始终使用抽象层。

Accessing pgSettings data in PostgreSQL在 PostgreSQL 中访问 pgSettings 数据​

With either of the above examples, you could write an SQL function get_x_something() to get the myapp.headers.x_something setting:

结合上述任一示例,你都可以编写一个 SQL 函数 get_x_something() 来获取 myapp.headers.x_something 配置项:

create function get_x_something() returns text as $$
select nullif(current_setting('myapp.headers.x_something', true), '')::text;
$$ language sql stable;

By default, everything in pgSettings is applied to the current transaction with set_config($key, $value, true); note that set_config only supports string values so it is best to only feed pgSettings string values (we’ll convert other values using the String() function, which may not have the effect you intend). All settings are automatically reset when the transaction completes.

默认情况下,pgSettings 中的所有内容都会通过 set_config($key, $value, true) 应用到当前事务中。请注意 set_config 仅支持字符串值,因此最好只向 pgSettings 传入字符串(对于其他类型的值,系统会使用 String() 函数进行转换,而转换结果未必符合你的预期)。所有配置都会在事务结束时自动重置。

Here’s an example of switching the PostgreSQL client into the ‘visitor’ role, and applying the application setting jwt.claims.user_id using the req.user object from an Express server:

下面是一个示例,演示如何在 Express 服务中将 PostgreSQL 客户端切换到 ‘visitor’ 角色,并使用来自 req.user 对象的数据设置应用变量 jwt.claims.user_id:

graphile.config.js
export default {
grafast: {
context(requestContext, args) {
// Base context used for all GraphQL requests
const context = {
pgSettings: {
...args.contextValue?.pgSettings,
role: "visitor",
},
};

// Extract the current user from the Express request:
const user = requestContext.expressv4?.req.user;

// If there's a user, pass additional data to Postgres:
if (user) {
context.pgSettings["jwt.claims.user_id"] = String(user.id);
}

return context;
},
},
};