# @grafserv/persisted 中文文档

规范地址：https://npmcn.com/package/%40grafserv/persisted/

版本：1\.0\.1
npm 元数据更新时间：2026-10-30T13:06:13.535Z
中文译文更新时间：2026-11-16T21:55:04.015Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40grafserv/persisted
原文对照：https://npmcn.com/package/%40grafserv/persisted/?lang=original
项目主页：https://github.com/graphile/crystal/tree/main/grafast/grafserv-persisted
源码仓库：https://github.com/graphile/crystal

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：33.1 kB，15 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=22
- 运行依赖：2 个
- peer 依赖：grafast ^1\.0\.0-rc\.8，graphql ^16\.9\.0，grafserv ^1\.0\.0-rc\.6，graphile-config ^1\.0\.0-rc\.5
- 首次发布：2023-04-26T14:38:37.495Z
- 最新版本发布：2026-10-30T13:06:12.909Z
- 近 30 天下载量：36307（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：84（近 12 个月 27 个）

## 中文简介

对Grafserv 的被动操作支持

## 安装

```sh
npm install @grafserv/persisted
```

也可以使用：`pnpm add @grafserv/persisted`、`yarn add @grafserv/persisted`、`bun add @grafserv/persisted`

## README

# @ grafserv/ 持久

[![GitHub Sponsors](https://img.shields.io/github/sponsors/benjie?color=ff69b4&label=github%20sponsors)](https://github.com/sponsors/benjie) [![Discord chat room](https://img.shields.io/discord/489127045289476126.svg)](http://discord.gg/graphile) [![Package on npm](https://img.shields.io/npm/v/@grafserv/persisted.svg?style=flat)](https://www.npmjs.com/package/@grafserv/persisted) ![MIT license](https://img.shields.io/npm/l/@grafserv/persisted.svg) [![Follow](https://img.shields.io/badge/BSky-@Graphile.org-006aff.svg)](https://bsky.app/profile/graphile.org) [![Follow](https://img.shields.io/badge/Mastodon-@Graphile.fosstodon.org-6364ff.svg)](https://fosstodon.org/@graphile)

模糊的操作( aka "persisted chests", "query limitlist", "persisted" ) 文档 ) [前进](https://grafast.org/grafserv)应用 无论是标准 GET 和 POST 请求,还是网络锁定连接。 为所有人服务 操作类型(取水口,突变和订阅).

我们建议所有 GraphQL 服务器(Post Graphile 或其他) 打算首先使用GraphQL计划的当事方客户应持续使用 减少对GraphQL API的攻击并帮助跟踪 字段。 这个包裹是Grafserv的解决方案 其他的 您需要不同的软件.

## 人群资助开源软件

为了帮助我们可持续地开发这一软件,我们请所有人和 \* 利用它来支持其持续维护与发展的企业 通过赞助.

### [点击这里了解更多关于赞助商和赞助商的情况.](https://www.graphile.org/sponsor/)

请给我们的赞助商一点爱

<table><tbody><tr><td align="center"><a href="https://gosteelhead.com/" rel="nofollow noopener noreferrer"><img alt="Steelhead" height="90" src="https://graphile.org/images/sponsors/steelhead.svg" width="90" loading="lazy" decoding="async" referrerpolicy="no-referrer"><br>钢头</a> * 联合国</td></tr></tbody></table>

_\* 赞助整个图形套间_

## 安装

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

## 使用量

导入 `PersistedPlugin` 从 `@grafserv/persisted` 然后加进 `plugins` 列表中 `graphile.config.ts` (或等同)文件:

```ts
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;
```

### 选项

此插件在 Grafserv 选项中添加了以下选项:

```ts
/**
 * 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);
```

所有这些选项都是可选的;但您应当精确指定其中之一 `persistedOperationsDirectory`, (中文(简体) ), `persistedOperations` 或者说 `persistedOperationsGetter` 用于此插件.

## 生成嵌入操作

### 中继

中继系统为持续开展的行动提供了内在支持:

[https://relay.dev/docs/guides/persisted-queries/ 页面存档备份,存于互联网档案馆](https://relay.dev/docs/guides/persisted-queries/)

过 `--persist-output ./path/to/server.json` 改为 `relay-compiler` 和 您的正常选项是生成持续操作文件。 你们可以 然后使用 `addToPersistedOperations.js` 下面的脚本可以分割此操作 JSON 文件写入每个查询可以传递到的文件 `--persisted-operations-directory`。 。 。 .

然后在您的网络配置中( E)`fetchQuery` 函数) `query: operation.text` 改为 `documentId: operation.id` [如中继文件所示](https://relay.dev/docs/guides/persisted-queries/#network-layer-changes)。 。 。 .

### 图QL 代码编辑器

除了"中继"之外,我们建议你做持续操作 当你用酷炫的建筑你的客户 [图克l-代码生成器](https://github.com/dotansimha/graphql-code-generator) 项目和 [图克l-编码-持久性-克赖里-标识](https://www.npmjs.com/package/graphql-codegen-persisted-query-ids) (通过v0.1.2插件测试). 一个配置可能看起来像:

```yaml
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
```

我们还建议使用文件 `addToPersistedOperations.js` 撰写 `server.json` 每次代码出现时, 文件内容会分开 GraphQL 文件 为方便版本控制而建 :

```js
// 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);
});
```

然后你通过 `.persisted_operations` 文件夹通过 `persistedOperationsDirectory` 选项,如使用示例所示.

#### 阿波罗客户端

您可以配置阿波罗客户端, 以发送由 `graphql-codegen` 与 `apollo-link-persisted-queries`数字 :

```ts
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 是什么？

对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 和提交记录判断。

