# @datocms/cda-client 中文文档

规范地址：https://npmcn.com/package/%40datocms/cda-client/

版本：0\.3\.2
npm 元数据更新时间：2026-09-04T09:07:25.550Z
中文译文更新时间：2026-11-11T15:31:55.971Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40datocms/cda-client
原文对照：https://npmcn.com/package/%40datocms/cda-client/?lang=original
项目主页：https://github.com/datocms/cda-client
源码仓库：https://github.com/datocms/cda-client

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

- 包体积（解压后）：169 kB，64 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- 首次发布：2024-07-25T08:32:49.482Z
- 最新版本发布：2026-09-04T09:07:25.370Z
- 近 30 天下载量：364960（2026-10-12 至 2026-11-10，npm 官方下载统计）
- 已发布版本数：21（近 12 个月 6 个）

## 中文简介

基于浏览器获取 API 的 DatoCMS GraphQL 内容交付 API 的 JS 客户端

## 安装

```sh
npm install @datocms/cda-client
```

也可以使用：`pnpm add @datocms/cda-client`、`yarn add @datocms/cda-client`、`bun add @datocms/cda-client`

## README

[![](https://www.datocms.com/images/full_logo.svg)](https://www.datocms.com/)

👉 [访问 DatoCMS 主页](https://www.datocms.com/) 或见 [达多CMS是什么?](https://npmcn.com/package/%40datocms/cda-client/#readme-what-is-datocms)

* * *

# @datocms/cda-客户端

一个轻量级, TypeScript 已准备好的软件包, 提供本地获取 API 周围的各种帮助, 执行 GraphQL 对 DatoCMS 的请求 [内容交付 API](https://www.datocms.com/docs/content-delivery-api)。 。 。 .

## 类型脚本支持

此软件包用TypeScript来构建,并提供出框的类型定义. 它支持 `TypedDocumentNode` 在使用时改进类型推论 [gql.tada (英语)](https://gql-tada.0no.co/), (中文(简体) ), [GraphQL 代码生成器](https://the-guild.dev/graphql/codegen) 或类似的工具.

## 实例

### 基本查询执行

```typescript
import { executeQuery } from "@datocms/cda-client";

const query = `
  query {
    allArticles {
      id
      title
    }
  }
`;

const result = await executeQuery(query, {
  token: "your-api-token-here",
});

console.log(result);
```

### 使用类型脚本和图形QL 代码生成器

```typescript
import { executeQuery } from "@datocms/cda-client";
import { AllArticlesQuery } from "./generated/graphql";

const result = await executeQuery(AllArticlesQuery, {
  token: "your-api-token-here",
  variables: {
    limit: 10,
  },
});

console.log(result.allArticles);
```

## 安装

```bash
npm install @datocms/cda-client
```

## 使用量

此软件包提供了多个工具功能来帮助您使用GraphQL与 DatoCMS 内容交付 API 交互.

### `executeQuery`

针对 DatoCMS 内容交付 API 执行 GraphQL 查询的主要功能 .

```typescript
import { executeQuery } from "@datocms/cda-client";

const result = await executeQuery(query, options);
```

#### 参数

-   `query`: GraphQL 查询字符串, `DocumentNode`,或 `TypedDocumentNode`。 。 。 .
-   `options`: 包含执行选项的对象.

#### 选项

| 选项 | 类型 | 说明 |
| --- | --- | --- |
| `token` | `string` | DatoCMS API 令牌( 需要) [更多信息](https://www.datocms.com/docs/content-delivery-api/authentication) |
| `includeDrafts` | `boolean` | 如果真实, 返回记录草稿 [更多信息](https://www.datocms.com/docs/content-delivery-api/api-endpoints#preview-mode-to-retrieve-draft-content) |
| `excludeInvalid` | `boolean` | 如果选中的话, 过滤无效的记录 [更多信息](https://www.datocms.com/docs/content-delivery-api/api-endpoints#strict-mode-for-non-nullable-graphql-types) |
| `environment` | `string` | 查询的 DatoCMS 环境名称 [更多信息](https://www.datocms.com/docs/content-delivery-api/api-endpoints#specifying-an-environment) |
| `contentLink` | `'vercel-v1'` | 如果真实, 嵌入内容链接的元数据 [更多信息](https://www.datocms.com/docs/content-delivery-api/api-endpoints#content-link) |
| `baseEditingUrl` | `string` | 您的 DatoCMS 项目的基础 URL [更多信息](https://www.datocms.com/docs/content-delivery-api/api-endpoints#content-link) |
| `returnCacheTags` | `boolean` | 如果为真, 则接收与查询相关的缓存标记 [更多信息](https://www.datocms.com/docs/content-delivery-api/api-endpoints#cache-tags) |
| `variables` | `object` | 要随查询一起发送的变量 |
| `fetchFn` | `function` | 自定义获取函数( 可选) |
| `requestInitOptions` | `Partial<RequestInit>` | 附加请求初始化选项( 可选) |
| `autoRetry` | `boolean` | 自动重试速度限制( 默认: 真) |

### `rawExecuteQuery`

类似 `executeQuery`,但返回查询结果和完整的响应对象。 当与 returnCacheTags 一起用于实际取回缓存标记时,此功能可以方便.

```typescript
import { rawExecuteQuery } from "@datocms/cda-client";

const [result, response] = await rawExecuteQuery(query, {
  token: "your-api-token-here",
  returnCacheTags: true,
});
const cacheTags = response.headers.get("x-cache-tags");
```

### `executeQueryWithAutoPagination`

当查询包含一个 pagized 收藏时, 此函数会很方便: 幕后, `executeQueryWithAutoPagination` 重修经过的查询并收集结果,以便 有可能获得超过Content Express API结果限制的唱片集合. 以透明的方式,用一个API的单一电话进行.

```typescript
import { executeQueryWithAutoPagination } from "@datocms/cda-client";

const result = await executeQueryWithAutoPagination(query, options);
```

#### 参数

参数相同,可用于: `executeQuery`数字 :

-   `query`: GraphQL 查询字符串, `DocumentNode`,或 `TypedDocumentNode`。 。 。 .
-   `options`: 包含具有相同形状的选项执行对象 `executeQuery`。 。 。 .

### 怎么会这样?

假设您想要在模型上执行以下查询: `2500` 记录 :

```graphql
query BuildSitemapUrls {
  allBlogPosts {
    slug
  }

  entries: allSuccessStories(first: 2500) {
    ...SuccessStoryUrlFragment
  }
}

fragment SuccessStoryUrlFragment on SuccessStoryRecord {
  slug
}
```

嗯,这是一个路障: CDA仅限于最多返回 `500` 一次的项目。 若想取取多取会出错. 相反,如果你想要得到所有 `2500` 记录中,通常您需要手动粘贴,执行多次查询,每次递增 `skip` 参数增加500。 干得可厉害了!

幸运的是, 帮助者的作用 `executeQueryWithAutoPagination` 以您的名义进行: 对上述查询进行分析,并像这样在苍蝇上重写:

```graphql
query BuildSitemapUrls {
  allBlogPosts {
    slug
  }
  splitted_0_entries: allSuccessStories(first: 500, skip: 0) {
    ...SuccessStoryUrlFragment
  }
  splitted_500_entries: allSuccessStories(first: 500, skip: 500) {
    ...SuccessStoryUrlFragment
  }
  splitted_1000_entries: allSuccessStories(first: 500, skip: 1000) {
    ...SuccessStoryUrlFragment
  }
  splitted_1500_entries: allSuccessStories(first: 500, skip: 1500) {
    ...SuccessStoryUrlFragment
  }
  splitted_2000_entries: allSuccessStories(first: 500, skip: 2000) {
    ...SuccessStoryUrlFragment
  }
}

fragment SuccessStoryUrlFragment on SuccessStoryRecord {
  slug
}
```

一旦执行,结果就会被收集和重新组合,仿佛什么都没有发生.

#### 限制

`executeQueryWithAutoPagination` 只有在查询中只包含一个选择 超规模 `first:` 参数(即: `first:` 参数超过了内容交付 API 的结果限制 `500`) (中文(简体) ). 如果两个或两个以上请求的模型有超大小的 pagination,函数会返回一个错误.

重写的查询仍必须尊重 [图QL复杂成本](https://www.datocms.com/docs/content-delivery-api/complexity)。 。 。 .

### `rawExecuteQueryWithAutoPagination`

至于 `executeQuery`,还有 `executeQueryWithAutoPagination` 拥有一对原始版本,既返回查询结果,又返回完整响应对象. 当与 returnCacheTags 一起用于实际取回缓存标记时,此功能可以方便.

```typescript
import { rawExecuteQueryWithAutoPagination } from "@datocms/cda-client";

const [result, response] = await rawExecuteQueryWithAutoPagination(query, {
  token: "your-api-token-here",
  returnCacheTags: true,
});
const cacheTags = response.headers.get("x-cache-tags");
```

### `buildRequestHeaders`

构建面向 DatoCMS 内容交付 API 的 GraphQL 查询请求头 .

```typescript
import { buildRequestHeaders } from "@datocms/cda-client";

const headers = buildRequestHeaders(options);
```

#### 选项

这个 `buildRequestHeaders` 函数接受的选项与 `executeQuery`时,除 `variables`, (中文(简体) ), `fetchFn`,以及 `autoRetry`。 。 。 .

### `buildRequestInit`

向 DatoCMS 内容交付 API 创建 GraphQL 查询的请求初始化对象.

```typescript
import { buildRequestInit } from "@datocms/cda-client";

const requestInit = buildRequestInit(query, options);
```

#### 参数

-   `query`: 图QL 查询字符串或 `DocumentNode`。 。 。 .
-   `options`: 含有执行选项的对象(与 `executeQuery`) (中文(简体) ).

## 处理错误

如果查询失败( 或使用 2xx 范围以外的 HTTP 状态代码, 或查询出错) , a `ApiError` 客户端会丢弃例外。 此错误包含请求和响应的所有细节, 允许您有效调试和处理错误 .

### 示例

```typescript
import { executeQuery, ApiError } from "@datocms/cda-client";

const query = `
  query {
    allArticles {
      id
      title
    }
  }
`;

try {
  const result = await executeQuery(query, {
    token: "your-api-token-here",
  });
  console.log(result);
} catch (e) {
  if (e instanceof ApiError) {
    // Information about the failed request. The API token is redacted from
    // `e.options`: an error tends to end up in logs and error trackers, which
    // are no place for a token.
    console.log(e.query);
    console.log(e.options);

    // Information about the response
    console.log(e.response.status);
    console.log(e.response.statusText);
    console.log(e.response.headers);
    console.log(e.response.body);
  } else {
    // Handle other types of errors
    throw e;
  }
}
```

## 捐款

欢迎捐款! 请随意提交拉力请求.

## 在发布前尝试改变

每推到这里的分行都会发布软件包的预览,您可以 任何地方安装——无 npm 发布,无 `npm link`数字 :

```
npm i https://pkg.pr.new/@datocms/cda-client@<commit-sha>
```

准确的 URL 出现在承诺的检查中 GitHub 上, 并出现在对 一旦出现拉力请求, 这是支持尝试改变的方法 在一个位于另一个存放处的场所里, 或者把一个固定给任何人 在释放前报告.

预览被丢弃:从未发布到 npm, URL停止 暂时解决。 永远不要把一个给一个 `package.json` 那个船.

## 释放(维护者)

每个用户可见的更改需要一个更改器: 运行 `npx changeset` 从还款 根在同一 PR 中,选择起伏级(`patch` 只用于错误修正, 新建 API 表面为 `minor`)并输入它所撰写的文件 `.changeset/`这是 更改日志条目的出处, 并且是决定起落关卡的地方 ——放假当天不行. 见 [`.changeset/README.md`](https://npmcn.com/package/%40datocms/cda-client/.changeset/README.md)。 。 。 .

释放,从最新,干净 `main`运行 `npm run release`。 构建和测试,应用待处理的更改器——接通版本和 写作 `CHANGELOG.md` ——发布到npm,只发布后标签 `vX.Y.Z`,推着, 并创建一个 GitHub 发布,其笔记直接来自该更改日志 输入。 中断的释放通过重新运行而恢复,永远不会被取消。 使用 `npm run release:next` 预释放 `next` dis.

脚本是 [`@datocms/release-toolchain`](https://github.com/datocms/release-toolchain), (中文(简体) ), 与其它所有 DatoCMS 存储器共享, 并在此被标记 .

## 许可证

这个项目根据麻省理工学院的许可证获得许可.

* * *

# 达多CMS是什么?

[![DatoCMS - The Headless CMS for the Modern Web](https://www.datocms.com/images/full_logo.svg)](https://www.datocms.com/)

[达多CMS](https://www.datocms.com/) 是现代网络的无头CMS。 由25,000+企业、机构和个人托管,它为您的团队提供了一个管理内容的地方,并通过API将其运送到任何网站、应用或设备.

**新来的?** 开始 [创建自由账户](https://dashboard.datocms.com/signup) 编辑 [文档](https://www.datocms.com/docs)粘着? 问 [社区](https://community.datocms.com/)好奇有什么新鲜事? [产品更新](https://www.datocms.com/product-updates)。 。 。 .

**建筑与AI:** [代理技能](https://www.datocms.com/docs/agent-skills) 将编码助理(Claude Code, Cursor)变成专家DatoCMS开发者,通过自动安装的CLI进行全读/写入. 没有本地终端? 使用 [MCP 服务器](https://www.datocms.com/docs/mcp-server) 换句话说.

**从代码对 DatoCMS 说话 :**

-   [内容交付 API](https://www.datocms.com/docs/content-delivery-api) (CDA) — 您的网站/应用程序的快速、 仅读 GraphQL API **获取** 已发布内容.
-   [内容管理 API](https://www.datocms.com/docs/content-management-api) (CMA) - REST API用于 **创建和更新** 内容、模型和项目设置(思维脚本、迁移、整合).
-   [国 际](https://www.datocms.com/docs/scripting-migrations/installing-the-cli) 用于图解迁移和从Contentful/WordPress导入的终端工具.

**框架指南:** 用于获取内容、渲染结构文本、优化图像/视频、处理SIO和设置视频编辑的现场预览 [下一个.js](https://www.datocms.com/docs/next-js), (中文(简体) ), [坚果](https://www.datocms.com/docs/nuxt), (中文(简体) ), [丝绒](https://www.datocms.com/docs/svelte),以及 [天体](https://www.datocms.com/docs/astro)。 。 。 .

**要先开始吗?** 浏览我们的 [启动项目](https://www.datocms.com/marketplace/starters) ——热门框架的现成部署示范站点.

## 常见问题

### @datocms/cda-client 是什么？

基于浏览器获取 API 的 DatoCMS GraphQL 内容交付 API 的 JS 客户端

### 如何安装 @datocms/cda-client？

在项目目录运行 npm install @datocms/cda-client，或使用 pnpm add / yarn add / bun add。

### @datocms/cda-client 支持 TypeScript 吗？

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

### @datocms/cda-client 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @datocms/cda-client 可以商用吗？

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

### @datocms/cda-client 的下载量有多少？

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

### @datocms/cda-client 还在维护吗？

最新版本 0\.3\.2 发布于 2026/09/04（2 个月前）；至今共发布 21 个版本，其中过去 12 个月发布了 6 个；首次发布于 2024/07/25。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

