datocms-cda

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

DatoCMS Content Delivery API Skill

DatoCMS Content Delivery API 技能指南

You are an expert at querying the DatoCMS Content Delivery API (CDA) using
@datocms/cda-client
. 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)完成。请按以下步骤依次操作,不要跳过任何步骤。

Step 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.
  1. Read
    package.json
    and check for
    @datocms/cda-client
    .
    • If not installed, recommend:
      npm install @datocms/cda-client
  2. Search for existing
    executeQuery
    or
    rawExecuteQuery
    imports to understand how the project already uses the CDA client.
  3. Check
    .env
    ,
    .env.local
    , or similar files for a DatoCMS API token. Look for variable names like:
    • DATOCMS_CDA_TOKEN
    • DATOCMS_READONLY_TOKEN
    • DATOCMS_API_TOKEN
    • NEXT_PUBLIC_DATOCMS_CDA_TOKEN
  4. 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.
  5. Check for existing type generation setup:
    • gql.tada: Look for
      gql.tada
      in
      package.json
      dependencies and an
      initGraphQLTada
      call (typically in
      lib/datocms/graphql.ts
      )
    • graphql-codegen: Look for
      @graphql-codegen/cli
      in devDependencies and a
      graphql.config.ts
      file
    • This detection is for context only — use it to write queries that match the project's existing setup (e.g., using the project's
      graphql()
      function instead of plain strings). Do not proactively suggest setting up type generation.
Important: The CDA needs a read-only API token (or a full-access CMA token, which also works). If you see a token named
DATOCMS_API_TOKEN
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.

如果本次对话中已确定项目上下文(客户端包、令牌变量、框架、类型生成配置),则跳过下面的宽泛检测步骤。仅当现有上下文无法回答问题时,才重新检查。
静默检查项目以确定其设置和配置:
  1. 读取
    package.json
    并检查是否包含
    @datocms/cda-client
    • 若未安装,建议执行:
      npm install @datocms/cda-client
  2. 搜索现有的
    executeQuery
    rawExecuteQuery
    导入,了解项目当前使用CDA客户端的方式。
  3. 检查
    .env
    .env.local
    或类似文件中的DatoCMS API令牌。查找以下变量名:
    • DATOCMS_CDA_TOKEN
    • DATOCMS_READONLY_TOKEN
    • DATOCMS_API_TOKEN
    • NEXT_PUBLIC_DATOCMS_CDA_TOKEN
  4. 检查框架上下文(Next.js、Astro、Remix、Nuxt、SvelteKit等),确定查询是在服务器端还是客户端运行。CDA查询在两种环境下均可运行,但除非项目有意使用公开的只读令牌,否则令牌不应暴露给浏览器。
  5. 检查现有的类型生成设置:
    • gql.tada:查看
      package.json
      依赖中是否包含
      gql.tada
      ,以及是否存在
      initGraphQLTada
      调用(通常位于
      lib/datocms/graphql.ts
    • graphql-codegen:查看开发依赖中是否包含
      @graphql-codegen/cli
      ,以及是否存在
      graphql.config.ts
      文件
    • 此检测仅用于获取上下文——据此编写与项目现有设置匹配的查询(例如,使用项目的
      graphql()
      函数而非纯字符串)。请勿主动建议设置类型生成。
重要提示:CDA需要只读API令牌(也可使用全权限CMA令牌,同样有效)。如果发现名为
DATOCMS_API_TOKEN
的令牌用于CMA操作,用户可能需要为CDA单独使用只读令牌,或在合适的情况下复用CMA令牌。

Step 2: Understand the Task

步骤2:理解任务

Classify the user's task into one or more categories:
CategoryExamples
Basic queryingFetch records by slug/ID, query single-instance models, list collections
FilteringFilter by field values, AND/OR logic, meta field filters, deep filtering
Pagination & orderingPaginate large collections, sort results, tree/hierarchical queries
LocalizationQuery localized fields, fallback locales, all-locale values
Modular contentQuery block fields with GraphQL fragments, nested blocks
Structured textQuery DAST value/blocks/links, render with framework components
Images & mediaResponsive images, imgix transforms, placeholders, focal points, video
SEO & meta
_seoMetaTags
, favicons,
globalSeo
, Open Graph tags
Draft/preview & cachingDraft mode, strict mode, cache tags, CDN invalidation, Content Link
Type generationSet 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与元数据
_seoMetaTags
、网站图标、
globalSeo
、Open Graph标签
草稿/预览与缓存草稿模式、严格模式、缓存标签、CDN失效、内容链接
类型生成设置gql.tada、配置graphql-codegen、生成 schema 类型、带类型的查询
如果用户的请求明确,可跳过澄清问题直接进行下一步。

Step 3: Load References

步骤3:加载参考资料

Based on the task classification, read the appropriate reference files from the
references/
directory next to this skill file. Always load the core client reference. Only load what is relevant — do not load everything.
Always load:
  • references/client-and-config.md
    — Client setup, options, error handling, limits, scalars
Load per category:
Task categoryReference file
Basic querying (records, collections, meta)
references/querying-basics.md
Filtering (field filters, AND/OR, deep filtering, uploads)
references/filtering.md
Pagination & ordering (first/skip, auto-pagination, trees)
references/pagination-and-ordering.md
Localization
references/localization.md
Modular content (blocks, fragments)
references/modular-content.md
Structured text (DAST, rendering)
references/structured-text.md
Images & media (responsiveImage, video)
references/images-and-videos.md
SEO & meta tags
references/seo-and-meta.md
Draft/preview, caching, environments, Content Link
references/draft-caching-environments.md
Type generation (gql.tada, graphql-codegen, schema types)
references/type-generation.md
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
    references/pagination-and-ordering.md
    for complexity costs

根据任务分类,读取本技能文件旁
references/
目录中的对应参考文件。务必加载核心客户端参考资料。仅加载相关内容——不要全部加载。
必须加载
  • references/client-and-config.md
    —— 客户端设置、选项、错误处理、限制、标量类型
按类别加载
任务类别参考文件
基础查询(记录、集合、元数据)
references/querying-basics.md
过滤(字段过滤、AND/OR、深度过滤、上传)
references/filtering.md
分页与排序(first/skip、自动分页、树形结构)
references/pagination-and-ordering.md
本地化
references/localization.md
模块化内容(区块、片段)
references/modular-content.md
结构化文本(DAST、渲染)
references/structured-text.md
图片与媒体(responsiveImage、视频)
references/images-and-videos.md
SEO与元标签
references/seo-and-meta.md
草稿/预览、缓存、环境、内容链接
references/draft-caching-environments.md
类型生成(gql.tada、graphql-codegen、schema类型)
references/type-generation.md
必要时加载跨领域参考资料
  • 若过滤本地化字段 → 同时加载
    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
    executeQuery
    from
    @datocms/cda-client
    , or the repo's existing wrapper around it (not raw
    fetch
    )
  • Use
    buildRequestHeaders()
    /
    buildRequestInit()
    when the framework needs integrated
    fetch
    handling, request tagging, or custom request plumbing
  • Use
    executeQueryWithAutoPagination
    when fetching more than 500 records
  • Use
    rawExecuteQuery
    only when you need response headers (e.g., cache tags)
  • 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
    ,
    inlineBlocks
    ) when the structured text field uses them — omitting any causes silent data loss
  • 当结构化文本字段使用相关子字段时,务必查询所有相关子字段
    value
    blocks
    links
    inlineBlocks
    )——省略任何一个都会导致静默数据丢失

Error Handling

错误处理

  • Catch
    ApiError
    from
    @datocms/cda-client
    at appropriate boundaries
  • Do not add custom retry logic —
    autoRetry
    handles rate limits automatically
  • 在合适的边界捕获
    @datocms/cda-client
    中的
    ApiError
  • 不要添加自定义重试逻辑——
    autoRetry
    会自动处理速率限制

TypeScript

TypeScript

  • Follow the TypeScript strictness rules: no
    as unknown as
    , no unnecessary
    as
    casts
  • Let TypeScript infer types wherever possible
  • Use
    import type { ... }
    for type-only imports

  • 遵循TypeScript严格规则:不使用
    as unknown as
    ,不使用不必要的
    as
    类型转换
  • 尽可能让TypeScript自动推断类型
  • 类型仅导入时使用
    import type { ... }

Step 5: Verify

步骤5:验证

Before presenting the final code:
  1. Token — Ensure the token comes from an environment variable and has read permissions
  2. Error handling — Ensure
    ApiError
    is caught at appropriate boundaries
  3. Pagination — If the collection could exceed 500 records, use
    executeQueryWithAutoPagination
  4. Draft mode — If
    includeDrafts
    is used, ensure it is intentional (not accidentally showing unpublished content in production)
  5. excludeInvalid
    — Recommend for stable schemas. If the schema is changing (migrations, new required fields), use
    filter: { _isValid: { eq: true } }
    instead to avoid re-validation errors
  6. Type safety — No type assertions (
    as
    ) used to silence errors
  7. Imports — CDA client imports come from
    @datocms/cda-client
    ; keep project-generated GraphQL helper imports when type generation is already wired
  8. Variables — All dynamic values use GraphQL variables, not string interpolation
  9. Structured text completeness — If querying structured text, all relevant sub-fields (
    value
    ,
    blocks
    ,
    links
    ,
    inlineBlocks
    ) are included
  10. Fetch integration — If the solution uses framework-native
    fetch
    , ensure CDA headers/init come from
    buildRequestHeaders()
    /
    buildRequestInit()
    instead of hand-rolled request wiring
  11. Type generation — If the project uses gql.tada or graphql-codegen, ensure queries use the project's
    graphql()
    function (not plain template literal strings) and that scalar mappings are configured

在展示最终代码前:
  1. 令牌——确保令牌来自环境变量且具备读取权限
  2. 错误处理——确保在合适的边界捕获
    ApiError
  3. 分页——如果集合可能超过500条记录,使用
    executeQueryWithAutoPagination
  4. 草稿模式——如果使用
    includeDrafts
    ,确保是有意为之(不要在生产环境意外显示未发布内容)
  5. excludeInvalid
    ——推荐用于稳定的schema。如果schema正在变更(迁移、新增必填字段),改用
    filter: { _isValid: { eq: true } }
    以避免重新验证错误
  6. 类型安全——不使用类型断言(
    as
    )来掩盖错误
  7. 导入——CDA客户端导入来自
    @datocms/cda-client
    ;当类型生成已配置时,保留项目生成的GraphQL辅助函数导入
  8. 变量——所有动态值使用GraphQL变量,而非字符串插值
  9. 结构化文本完整性——如果查询结构化文本,确保包含所有相关子字段(
    value
    blocks
    links
    inlineBlocks
  10. Fetch集成——如果解决方案使用框架原生
    fetch
    ,确保CDA请求头/初始化配置来自
    buildRequestHeaders()
    /
    buildRequestInit()
    ,而非手动编写的请求流程
  11. 类型生成——如果项目使用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:
ConditionRoute 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 frameworkdatocms-frontend-integrations
Building a DatoCMS plugindatocms-plugin-builder
本技能涵盖通过GraphQL CDA读取内容。如果任务涉及以下任一情况,请激活配套技能:
条件路由至
修改内容、管理schema/上传/ webhook、编写脚本(包括通过REST查询记录的脚本)datocms-cma
在框架中设置草稿模式端点、Web预览、内容链接、实时订阅或缓存标签datocms-frontend-integrations
构建DatoCMS插件datocms-plugin-builder