datocms-cda
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDatoCMS Content Delivery API Skill
DatoCMS Content Delivery API 技能指南
You are an expert at querying the DatoCMS Content Delivery API (CDA) using . The CDA is a read-only GraphQL API — it has no mutations. All content changes go through the CMA (Content Management API). Follow these steps in order. Do not skip steps.
@datocms/cda-client你是使用查询DatoCMS内容交付API(CDA)的专家。CDA是一个只读GraphQL API——不支持变更操作。所有内容修改需通过CMA(内容管理API)完成。请按以下步骤依次操作,不要跳过任何步骤。
@datocms/cda-clientStep 1: Detect Context
步骤1:检测上下文
If the project context is already established in this conversation (client
package, token variable, framework, type generation setup), skip broad
detection below. Re-inspect only when a question cannot be answered from
prior context.
Silently examine the project to determine setup and configuration.
-
Readand check for
package.json.@datocms/cda-client- If not installed, recommend:
npm install @datocms/cda-client
- If not installed, recommend:
-
Search for existingor
executeQueryimports to understand how the project already uses the CDA client.rawExecuteQuery -
Check,
.env, or similar files for a DatoCMS API token. Look for variable names like:.env.localDATOCMS_CDA_TOKENDATOCMS_READONLY_TOKENDATOCMS_API_TOKENNEXT_PUBLIC_DATOCMS_CDA_TOKEN
-
Check the framework context (Next.js, Astro, Remix, Nuxt, SvelteKit, etc.) to determine whether queries run on the server or client. CDA queries work in both environments, but tokens should not be exposed to the browser unless the project intentionally uses a public read-only token.
-
Check for existing type generation setup:
- gql.tada: Look for in
gql.tadadependencies and anpackage.jsoncall (typically ininitGraphQLTada)lib/datocms/graphql.ts - graphql-codegen: Look for in devDependencies and a
@graphql-codegen/clifilegraphql.config.ts - This detection is for context only — use it to write queries that match the project's existing setup (e.g., using the project's function instead of plain strings). Do not proactively suggest setting up type generation.
graphql()
- gql.tada: Look for
Important: The CDA needs a read-only API token (or a full-access CMA token, which also works). If you see a token named used for CMA operations, the user may need a separate read-only token for the CDA, or they can reuse the CMA token if appropriate.
DATOCMS_API_TOKEN如果本次对话中已确定项目上下文(客户端包、令牌变量、框架、类型生成配置),则跳过下面的宽泛检测步骤。仅当现有上下文无法回答问题时,才重新检查。
静默检查项目以确定其设置和配置:
-
读取并检查是否包含
package.json。@datocms/cda-client- 若未安装,建议执行:
npm install @datocms/cda-client
- 若未安装,建议执行:
-
搜索现有的或
executeQuery导入,了解项目当前使用CDA客户端的方式。rawExecuteQuery -
检查、
.env或类似文件中的DatoCMS API令牌。查找以下变量名:.env.localDATOCMS_CDA_TOKENDATOCMS_READONLY_TOKENDATOCMS_API_TOKENNEXT_PUBLIC_DATOCMS_CDA_TOKEN
-
检查框架上下文(Next.js、Astro、Remix、Nuxt、SvelteKit等),确定查询是在服务器端还是客户端运行。CDA查询在两种环境下均可运行,但除非项目有意使用公开的只读令牌,否则令牌不应暴露给浏览器。
-
检查现有的类型生成设置:
- gql.tada:查看依赖中是否包含
package.json,以及是否存在gql.tada调用(通常位于initGraphQLTada)lib/datocms/graphql.ts - graphql-codegen:查看开发依赖中是否包含,以及是否存在
@graphql-codegen/cli文件graphql.config.ts - 此检测仅用于获取上下文——据此编写与项目现有设置匹配的查询(例如,使用项目的函数而非纯字符串)。请勿主动建议设置类型生成。
graphql()
- gql.tada:查看
重要提示:CDA需要只读API令牌(也可使用全权限CMA令牌,同样有效)。如果发现名为的令牌用于CMA操作,用户可能需要为CDA单独使用只读令牌,或在合适的情况下复用CMA令牌。
DATOCMS_API_TOKENStep 2: Understand the Task
步骤2:理解任务
Classify the user's task into one or more categories:
| Category | Examples |
|---|---|
| Basic querying | Fetch records by slug/ID, query single-instance models, list collections |
| Filtering | Filter by field values, AND/OR logic, meta field filters, deep filtering |
| Pagination & ordering | Paginate large collections, sort results, tree/hierarchical queries |
| Localization | Query localized fields, fallback locales, all-locale values |
| Modular content | Query block fields with GraphQL fragments, nested blocks |
| Structured text | Query DAST value/blocks/links, render with framework components |
| Images & media | Responsive images, imgix transforms, placeholders, focal points, video |
| SEO & meta | |
| Draft/preview & caching | Draft mode, strict mode, cache tags, CDN invalidation, Content Link |
| Type generation | Set up gql.tada, configure graphql-codegen, generate schema types, typed queries |
If the user's request is clear, skip clarifying questions and proceed directly.
将用户的任务归类为一个或多个类别:
| 类别 | 示例 |
|---|---|
| 基础查询 | 通过slug/ID获取记录、查询单实例模型、列出集合 |
| 过滤 | 按字段值过滤、AND/OR逻辑、元字段过滤、深度过滤 |
| 分页与排序 | 对大型集合分页、排序结果、树形/层级查询 |
| 本地化 | 查询本地化字段、回退语言、多语言值 |
| 模块化内容 | 使用GraphQL片段查询区块字段、嵌套区块 |
| 结构化文本 | 查询DAST值/区块/链接、使用框架组件渲染 |
| 图片与媒体 | 响应式图片、imgix转换、占位符、焦点、视频 |
| SEO与元数据 | |
| 草稿/预览与缓存 | 草稿模式、严格模式、缓存标签、CDN失效、内容链接 |
| 类型生成 | 设置gql.tada、配置graphql-codegen、生成 schema 类型、带类型的查询 |
如果用户的请求明确,可跳过澄清问题直接进行下一步。
Step 3: Load References
步骤3:加载参考资料
Based on the task classification, read the appropriate reference files from the directory next to this skill file. Always load the core client reference. Only load what is relevant — do not load everything.
references/Always load:
- — Client setup, options, error handling, limits, scalars
references/client-and-config.md
Load per category:
| Task category | Reference file |
|---|---|
| Basic querying (records, collections, meta) | |
| Filtering (field filters, AND/OR, deep filtering, uploads) | |
| Pagination & ordering (first/skip, auto-pagination, trees) | |
| Localization | |
| Modular content (blocks, fragments) | |
| Structured text (DAST, rendering) | |
| Images & media (responsiveImage, video) | |
| SEO & meta tags | |
| Draft/preview, caching, environments, Content Link | |
| Type generation (gql.tada, graphql-codegen, schema types) | |
Load cross-cutting references when needed:
- If filtering localized fields → also load
references/localization.md - If querying modular content inside structured text → also load
references/modular-content.md - If querying images inside blocks → also load
references/images-and-videos.md - If paginating a large filtered collection → also load
references/pagination-and-ordering.md - If the query involves complex nesting → also load for complexity costs
references/pagination-and-ordering.md
根据任务分类,读取本技能文件旁目录中的对应参考文件。务必加载核心客户端参考资料。仅加载相关内容——不要全部加载。
references/必须加载:
- —— 客户端设置、选项、错误处理、限制、标量类型
references/client-and-config.md
按类别加载:
| 任务类别 | 参考文件 |
|---|---|
| 基础查询(记录、集合、元数据) | |
| 过滤(字段过滤、AND/OR、深度过滤、上传) | |
| 分页与排序(first/skip、自动分页、树形结构) | |
| 本地化 | |
| 模块化内容(区块、片段) | |
| 结构化文本(DAST、渲染) | |
| 图片与媒体(responsiveImage、视频) | |
| SEO与元标签 | |
| 草稿/预览、缓存、环境、内容链接 | |
| 类型生成(gql.tada、graphql-codegen、schema类型) | |
必要时加载跨领域参考资料:
- 若过滤本地化字段 → 同时加载
references/localization.md - 若查询结构化文本中的模块化内容 → 同时加载
references/modular-content.md - 若查询区块中的图片 → 同时加载
references/images-and-videos.md - 若对大型过滤集合分页 → 同时加载
references/pagination-and-ordering.md - 若查询涉及复杂嵌套 → 同时加载了解复杂度成本
references/pagination-and-ordering.md
Step 4: Generate Code
步骤4:生成代码
Write the code following these mandatory rules:
编写代码时需遵循以下强制规则:
Client Usage
客户端使用
- Default to from
executeQuery, or the repo's existing wrapper around it (not raw@datocms/cda-client)fetch - Use /
buildRequestHeaders()when the framework needs integratedbuildRequestInit()handling, request tagging, or custom request plumbingfetch - Use when fetching more than 500 records
executeQueryWithAutoPagination - Use only when you need response headers (e.g., cache tags)
rawExecuteQuery - Store the API token in an environment variable — never hardcode it
- 默认使用:来自
executeQuery,或仓库中已有的封装函数(而非原生@datocms/cda-client)fetch - 当框架需要集成处理、请求标记或自定义请求流程时,使用
fetch/buildRequestHeaders()buildRequestInit() - 当获取超过500条记录时,使用****
executeQueryWithAutoPagination - 仅当需要响应头(例如缓存标签)时,使用****
rawExecuteQuery - 将API令牌存储在环境变量中——绝对不要硬编码
GraphQL Queries
GraphQL查询
- Write queries as template literal strings (unless the project uses /
TypedDocumentNode)gql.tada - Use GraphQL variables for all dynamic values — never use string interpolation in queries
- Request only the fields you need — do not over-fetch
- Use DatoCMS custom scalars in variable declarations (e.g., ,
$first: IntType)$id: ItemId
- 将查询编写为模板字面量字符串(除非项目使用/
TypedDocumentNode)gql.tada - 所有动态值使用GraphQL变量——绝对不要在查询中使用字符串插值
- 仅请求所需字段——避免过度获取
- 在变量声明中使用DatoCMS自定义标量类型(例如、
$first: IntType)$id: ItemId
Structured Text
结构化文本
- Always query all relevant sub-fields (,
value,blocks,links) when the structured text field uses them — omitting any causes silent data lossinlineBlocks
- 当结构化文本字段使用相关子字段时,务必查询所有相关子字段(、
value、blocks、links)——省略任何一个都会导致静默数据丢失inlineBlocks
Error Handling
错误处理
- Catch from
ApiErrorat appropriate boundaries@datocms/cda-client - Do not add custom retry logic — handles rate limits automatically
autoRetry
- 在合适的边界捕获中的
@datocms/cda-clientApiError - 不要添加自定义重试逻辑——会自动处理速率限制
autoRetry
TypeScript
TypeScript
- Follow the TypeScript strictness rules: no , no unnecessary
as unknown ascastsas - Let TypeScript infer types wherever possible
- Use for type-only imports
import type { ... }
- 遵循TypeScript严格规则:不使用,不使用不必要的
as unknown as类型转换as - 尽可能让TypeScript自动推断类型
- 类型仅导入时使用
import type { ... }
Step 5: Verify
步骤5:验证
Before presenting the final code:
- Token — Ensure the token comes from an environment variable and has read permissions
- Error handling — Ensure is caught at appropriate boundaries
ApiError - Pagination — If the collection could exceed 500 records, use
executeQueryWithAutoPagination - Draft mode — If is used, ensure it is intentional (not accidentally showing unpublished content in production)
includeDrafts - — Recommend for stable schemas. If the schema is changing (migrations, new required fields), use
excludeInvalidinstead to avoid re-validation errorsfilter: { _isValid: { eq: true } } - Type safety — No type assertions () used to silence errors
as - Imports — CDA client imports come from ; keep project-generated GraphQL helper imports when type generation is already wired
@datocms/cda-client - Variables — All dynamic values use GraphQL variables, not string interpolation
- Structured text completeness — If querying structured text, all relevant sub-fields (,
value,blocks,links) are includedinlineBlocks - Fetch integration — If the solution uses framework-native , ensure CDA headers/init come from
fetch/buildRequestHeaders()instead of hand-rolled request wiringbuildRequestInit() - Type generation — If the project uses gql.tada or graphql-codegen, ensure queries use the project's function (not plain template literal strings) and that scalar mappings are configured
graphql()
在展示最终代码前:
- 令牌——确保令牌来自环境变量且具备读取权限
- 错误处理——确保在合适的边界捕获
ApiError - 分页——如果集合可能超过500条记录,使用
executeQueryWithAutoPagination - 草稿模式——如果使用,确保是有意为之(不要在生产环境意外显示未发布内容)
includeDrafts - ——推荐用于稳定的schema。如果schema正在变更(迁移、新增必填字段),改用
excludeInvalid以避免重新验证错误filter: { _isValid: { eq: true } } - 类型安全——不使用类型断言()来掩盖错误
as - 导入——CDA客户端导入来自;当类型生成已配置时,保留项目生成的GraphQL辅助函数导入
@datocms/cda-client - 变量——所有动态值使用GraphQL变量,而非字符串插值
- 结构化文本完整性——如果查询结构化文本,确保包含所有相关子字段(、
value、blocks、links)inlineBlocks - Fetch集成——如果解决方案使用框架原生,确保CDA请求头/初始化配置来自
fetch/buildRequestHeaders(),而非手动编写的请求流程buildRequestInit() - 类型生成——如果项目使用gql.tada或graphql-codegen,确保查询使用项目的函数(而非纯模板字面量字符串),且已配置标量映射
graphql()
Cross-Skill Routing
跨技能路由
This skill covers reading content via the GraphQL CDA. If the task involves any of the following, activate the companion skill:
| Condition | Route to |
|---|---|
| Mutating content, managing schema/uploads/webhooks, writing scripts (including querying records via REST for scripts) | datocms-cma |
| Setting up draft mode endpoints, Web Previews, Content Link, real-time subscriptions, or cache tags in a framework | datocms-frontend-integrations |
| Building a DatoCMS plugin | datocms-plugin-builder |
本技能涵盖通过GraphQL CDA读取内容。如果任务涉及以下任一情况,请激活配套技能:
| 条件 | 路由至 |
|---|---|
| 修改内容、管理schema/上传/ webhook、编写脚本(包括通过REST查询记录的脚本) | datocms-cma |
| 在框架中设置草稿模式端点、Web预览、内容链接、实时订阅或缓存标签 | datocms-frontend-integrations |
| 构建DatoCMS插件 | datocms-plugin-builder |