@grafserv/persisted

中文文档
1.0.1发布于 2026/10/30MITTypeScriptCommonJS构建来源已验证近 30 天下载 3.6万

Persisted operations support for Grafserv

原始使用文档
文档目录8 节
  1. Crowd-funded open-source software
  2. Click here to find out more about sponsors and sponsorship.
  3. Installation
  4. Usage
  5. Options
  6. Generating Persisted Operations
  7. Relay
  8. GraphQL-Code-Generator

@grafserv/persisted

GitHub Sponsors Discord chat room Package on npm MIT license Follow Follow

Persisted operations (aka "persisted queries", "query allowlist", "persisted documents") support for Grafserv. Applies to both standard GET and POST requests and to websocket connections. Works for all operation types (queries, mutations and subscriptions).

We recommend that all GraphQL servers (PostGraphile or otherwise) that only intend first party clients to use the GraphQL schema should use persisted operations to mitigate attacks against the GraphQL API and to help track the fields that have been used. This package is our solution for Grafserv, for other servers you will need different software.

Crowd-funded open-source software

To help us develop this software sustainably, we ask all individuals and businesses that use it to help support its ongoing maintenance and development via sponsorship.

Click here to find out more about sponsors and sponsorship.

And please give some love to our featured sponsors 🤩:

Steelhead
Steelhead
*

* Sponsors the entire Graphile suite

Installation

yarn add @grafserv/persisted
# or: npm install --save @grafserv/persisted

Usage

Import PersistedPlugin from @grafserv/persisted and then add it to the plugins list in your graphile.config.ts (or equivalent) file:

import "graphile-config";
import PersistedPlugin from "@grafserv/persisted";

const preset: GraphileConfig.Preset = {
  plugins: [PersistedPlugin],
  grafserv: {
    /* add configuration options here, e.g. */
    persistedOperationsDirectory: `${process.cwd()}/.persisted_operations`,
  },
};

export default preset;

Options

This plugin adds the following options to the Grafserv options:

/**
 * This function will be passed a GraphQL request object (normally
 * `{query: string, variables?: any, operationName?: string, extensions?: any}`,
 * but in the case of persisted operations it likely won't have a `query`
 * property), and must extract the hash to use to identify the persisted
 * operation. For Apollo Client, this might be something like:
 * `request?.extensions?.persistedQuery?.sha256Hash`; for Relay something
 * like: `request?.documentId`.
 */
hashFromPayload?(request: ParsedGraphQLBody): string | undefined;

/**
 * We can read persisted operations from a folder (they must be named
 * `<hash>.graphql`). When used in this way, the first request for a hash
 * will read the file, and then the result will be cached such that the
 * **filesystem read** will only impact the first use of that hash. We
 * periodically scan the folder for new files, requests for hashes that
 * were not present in our last scan of the folder will be rejected to
 * mitigate denial of service attacks asking for non-existent hashes.
 */
persistedOperationsDirectory?: string;

/**
 * An optional string-string key-value object defining the persisted
 * operations, where the keys are the hashes, and the values are the
 * operation document strings to use.
 */
persistedOperations?: { [hash: string]: string };

/**
 * If your known persisted operations may change over time, or you'd rather
 * load them on demand, you may supply this function. Note this function is
 * **performance critical** so you should use caching to improve
 * performance of any follow-up requests for the same hash.
 */
persistedOperationsGetter?: PersistedOperationGetter;

/**
 * There are situations where you may want to allow arbitrary operations
 * (for example using GraphiQL in development, or allowing an admin to
 * make arbitrary requests in production) whilst enforcing Persisted
 * Operations for the application and non-admin users. This function
 * allows you to determine under which circumstances persisted operations
 * may be bypassed.
 *
 * IMPORTANT: this function must not throw!
 *
 * @example
 *
 * ```
 * app.use(postgraphile(DATABASE_URL, SCHEMAS, {
 *   allowUnpersistedOperation(event) {
 *     return process.env.NODE_ENV === "development" && event.request?.getHeader('referer')?.endsWith("/graphiql");
 *   }
 * });
 * ```
 */
allowUnpersistedOperation?:
  | boolean
  | ((event: ProcessGraphQLRequestBodyEvent) => boolean);

All these options are optional; but you should specify exactly one of persistedOperationsDirectory, persistedOperations or persistedOperationsGetter for this plugin to be useful.

Generating Persisted Operations

Relay

Relay has built-in support for persisted operations:

https://relay.dev/docs/guides/persisted-queries/

Pass --persist-output ./path/to/server.json to relay-compiler along with your normal options to have it generate the persisted operations file. You can then use the addToPersistedOperations.js script below to split this operations JSON file into one file per query that can be passed to --persisted-operations-directory.

Then in your network config (fetchQuery function) you need to change the query: operation.text to documentId: operation.id as shown in the relay docs.

GraphQL-Code-Generator

For everything except Relay, we recommend that you generate persisted operations when you build your clients using the awesome graphql-code-generator project and the graphql-codegen-persisted-query-ids (tested with v0.1.2) plugin. A config might look like:

schema: "schema.graphql"
documents: "src/**/*.graphql"
hooks:
  afterAllFileWrite:
    - node addToPersistedOperations.js
generates:
  client.json:
    plugins:
      - graphql-codegen-persisted-query-ids:
          output: client
          algorithm: sha256
  server.json:
    plugins:
      - graphql-codegen-persisted-query-ids:
          output: server
          algorithm: sha256

We also recommend using the file addToPersistedOperations.js to write the server.json file contents out to separate GraphQL files every time the code is built for easier version control:

// addToPersistedOperations.js
const map = require("./server.json");
const { promises: fsp } = require("fs");

async function main() {
  await Promise.all(
    Object.entries(map).map(([hash, query]) =>
      fsp.writeFile(
        `${__dirname}/.persisted_operations/${hash}.graphql`,
        query,
      ),
    ),
  );
}

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

Then you pass the .persisted_operations folder via the persistedOperationsDirectory option as shown in the usage example.

Apollo Client

You can configure Apollo Client to send the persisted operations generated by graphql-codegen with apollo-link-persisted-queries:

import { createPersistedQueryLink } from "apollo-link-persisted-queries";
import { usePregeneratedHashes as withPregeneratedHashes } from "graphql-codegen-persisted-query-ids/lib/apollo";
import { hashes } from "./path/to/client.json";

const persistedLink = createPersistedQueryLink({
  useGETForHashedQueries: false,
  generateHash: withPregeneratedHashes(hashes),
  disable: () => false,
});

// ...

const client = new ApolloClient({
  link: ApolloLink.from([persistedLink, httpLink]),
  // ...
});

版本与发布记录

@grafserv/persisted 共发布 84 个版本,首次发布于 2023/04/26;过去 12 个月发布了 27 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.0.1latest2026/10/3017 天前
1.0.1-aardvark.next-20260928202932snapshot-next2026/09/291 个月前
1.0.1-aardvark.next-202609251642492026/09/261 个月前
1.0.1-aardvark.next-202609222244162026/09/231 个月前
1.0.1-aardvark.next-202609191851302026/09/201 个月前
1.0.1-aardvark.next-202609180853272026/09/181 个月前

其他发布通道:prealpha → 0.0.0-alpha.2,alpha → 0.0.0-alpha.17,beta → 0.0.0-beta.38,rc → 1.0.0-rc.7,snapshot-next → 1.0.1-aardvark.next-20260928202932。

关于 @grafserv/persisted 的常见问题

@grafserv/persisted 是什么?

Persisted operations support for Grafserv

如何安装 @grafserv/persisted?

在项目目录运行 npm install @grafserv/persisted,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:grafast(^1.0.0-rc.8)、graphql(^16.9.0)、grafserv(^1.0.0-rc.6)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@grafserv/persisted 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@grafserv/persisted 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@grafserv/persisted 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@grafserv/persisted 可以商用吗?

@grafserv/persisted 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@grafserv/persisted 的下载量有多少?

根据 npm 官方下载统计,@grafserv/persisted 在 2026/10/17 – 2026/11/15 这 30 天内被下载 36,307 次,日均约 1,210 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@grafserv/persisted 还在维护吗?

最新版本 1.0.1 发布于 2026/10/30(17 天前);至今共发布 84 个版本,其中过去 12 个月发布了 27 个;首次发布于 2023/04/26。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。