datocms

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

DatoCMS Agent Skill

DatoCMS Agent 技能

This skill provides comprehensive guidance for working with DatoCMS, a headless CMS platform. It combines decision frameworks, executable workflows, and complete documentation reference.
本技能为使用DatoCMS(一款无头CMS平台)提供全面指导,结合了决策框架、可执行工作流和完整的文档参考。

When to Use This Skill

何时使用本技能

Use this skill when:
  • Building or maintaining a DatoCMS project
  • Integrating DatoCMS with frameworks (Next.js, React, Vue, etc.)
  • Managing content models, records, or assets via API
  • Setting up webhooks or real-time updates
  • Working with DatoCMS plugins or the Plugin SDK
  • Migrating content or managing multiple environments
  • Troubleshooting DatoCMS API or integration issues
Do NOT use this skill for:
  • Generic CMS comparisons (unless DatoCMS-specific)
  • Non-DatoCMS headless CMS implementations
  • Basic frontend development unrelated to DatoCMS
在以下场景使用本技能:
  • 构建或维护DatoCMS项目
  • 将DatoCMS与框架集成(Next.js、React、Vue等)
  • 通过API管理内容模型、记录或资产
  • 设置Webhooks或实时更新
  • 使用DatoCMS插件或Plugin SDK
  • 迁移内容或管理多环境
  • 排查DatoCMS API或集成问题
请勿在以下场景使用本技能:
  • 通用CMS对比(除非是DatoCMS特定的对比)
  • 非DatoCMS的无头CMS实现
  • 与DatoCMS无关的基础前端开发

API Decision Guide

API决策指南

DatoCMS provides multiple APIs for different use cases:
DatoCMS为不同使用场景提供了多种API:

Content Delivery API (CDA)

内容交付API(CDA)

Use for: Fetching published content for production sites
  • GraphQL-based, read-only
  • Optimized for speed with global CDN
  • Supports filtering, sorting, pagination
  • Best for: SSR, SSG, client-side fetching
Example:
typescript
import { executeQuery } from '@datocms/cda-client';

const result = await executeQuery(query, {
  token: process.env.DATOCMS_API_TOKEN,
  environment: 'main'
});
适用场景: 为生产站点获取已发布内容
  • 基于GraphQL,只读
  • 经全球CDN优化,速度更快
  • 支持过滤、排序、分页
  • 最佳使用场景:SSR、SSG、客户端数据获取
示例:
typescript
import { executeQuery } from '@datocms/cda-client';

const result = await executeQuery(query, {
  token: process.env.DATOCMS_API_TOKEN,
  environment: 'main'
});

Content Management API (CMA)

内容管理API(CMA)

Use for: Creating, updating, deleting content and schema
  • REST-based with full CRUD operations
  • Requires write permissions
  • Best for: Admin panels, migrations, automated content creation
Example:
typescript
import { buildClient } from '@datocms/cma-client-node';

const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });

// Create a record
const record = await client.items.create({
  item_type: { type: 'item_type', id: 'blog_post' },
  title: 'New Post',
  content: 'Content here'
});
适用场景: 创建、更新、删除内容和架构
  • 基于REST,支持完整CRUD操作
  • 需要写入权限
  • 最佳使用场景:管理面板、迁移、自动化内容创建
示例:
typescript
import { buildClient } from '@datocms/cma-client-node';

const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });

// 创建记录
const record = await client.items.create({
  item_type: { type: 'item_type', id: 'blog_post' },
  title: 'New Post',
  content: 'Content here'
});

Asset API

资产API

Use for: Uploading files and managing assets
  • Two-step process: request upload URL, then upload file
  • Supports images, videos, documents
适用场景: 上传文件和管理资产
  • 两步流程:请求上传URL,然后上传文件
  • 支持图片、视频、文档

Real-Time Updates API

实时更新API

Use for: Live preview, collaborative editing
  • WebSocket-based
  • Reflects draft changes instantly
适用场景: 实时预览、协作编辑
  • 基于WebSocket
  • 即时反映草稿变更

Getting Started

快速入门

1. API Tokens

1. API令牌

  • Go to Settings > API Tokens in your DatoCMS project
  • Read-only token for CDA (can be public)
  • Full-access token for CMA (keep secret)
  • 进入DatoCMS项目的“设置 > API令牌”页面
  • 只读令牌用于CDA(可公开)
  • 全权限令牌用于CMA(需保密)

2. Install Clients

2. 安装客户端

bash
undefined
bash
undefined

For content fetching

用于内容获取

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

For content management

用于内容管理

npm install @datocms/cma-client-node
npm install @datocms/cma-client-node

For React/Next.js

用于React/Next.js

npm install react-datocms
undefined
npm install react-datocms
undefined

3. Basic Query

3. 基础查询

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

const query = `
  query {
    allBlogPosts {
      id
      title
      slug
      publishedAt
    }
  }
`;

const data = await executeQuery(query, {
  token: process.env.DATOCMS_API_TOKEN
});
typescript
import { executeQuery } from '@datocms/cda-client';

const query = `
  query {
    allBlogPosts {
      id
      title
      slug
      publishedAt
    }
  }
`;

const data = await executeQuery(query, {
  token: process.env.DATOCMS_API_TOKEN
});

Workflow Playbooks

工作流手册

1. Schema Management: Create Models & Fields

1. 架构管理:创建模型与字段

When: Setting up new content types or modifying existing ones
typescript
import { buildClient } from '@datocms/cma-client-node';

const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });

// Create a model
const model = await client.itemTypes.create({
  name: 'Blog Post',
  api_key: 'blog_post',
  singleton: false
});

// Add fields
await client.fields.create(model.id, {
  label: 'Title',
  field_type: 'string',
  api_key: 'title',
  validators: { required: {} }
});

await client.fields.create(model.id, {
  label: 'Content',
  field_type: 'structured_text',
  api_key: 'content'
});
适用场景: 设置新内容类型或修改现有类型
typescript
import { buildClient } from '@datocms/cma-client-node';

const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });

// 创建模型
const model = await client.itemTypes.create({
  name: 'Blog Post',
  api_key: 'blog_post',
  singleton: false
});

// 添加字段
await client.fields.create(model.id, {
  label: 'Title',
  field_type: 'string',
  api_key: 'title',
  validators: { required: {} }
});

await client.fields.create(model.id, {
  label: 'Content',
  field_type: 'structured_text',
  api_key: 'content'
});

2. Content Operations: CRUD + Publishing

2. 内容操作:CRUD与发布

When: Managing content records programmatically
typescript
// Create draft
const draft = await client.items.create({
  item_type: { type: 'item_type', id: 'blog_post' },
  title: 'My Post',
  content: { /* DAST structure */ }
});

// Update
await client.items.update(draft.id, {
  title: 'Updated Title'
});

// Publish
await client.items.publish(draft.id);

// Unpublish
await client.items.unpublish(draft.id);

// Delete
await client.items.destroy(draft.id);
适用场景: 以编程方式管理内容记录
typescript
// 创建草稿
const draft = await client.items.create({
  item_type: { type: 'item_type', id: 'blog_post' },
  title: 'My Post',
  content: { /* DAST结构 */ }
});

// 更新
await client.items.update(draft.id, {
  title: 'Updated Title'
});

// 发布
await client.items.publish(draft.id);

// 取消发布
await client.items.unpublish(draft.id);

// 删除
await client.items.destroy(draft.id);

3. Asset Uploads: Two-Step Flow

3. 资产上传:两步流程

When: Uploading images, videos, or documents
typescript
import { buildClient } from '@datocms/cma-client-node';
import fs from 'fs';

const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });

// Step 1: Create upload request
const path = './image.jpg';
const uploadRequest = await client.uploads.createFromFileOrBlob({
  fileOrBlob: fs.createReadStream(path),
  filename: 'image.jpg'
});

// Step 2: Use upload in a record
await client.items.create({
  item_type: { type: 'item_type', id: 'blog_post' },
  title: 'Post with Image',
  cover_image: {
    upload_id: uploadRequest.id
  }
});
适用场景: 上传图片、视频或文档
typescript
import { buildClient } from '@datocms/cma-client-node';
import fs from 'fs';

const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });

// 步骤1:创建上传请求
const path = './image.jpg';
const uploadRequest = await client.uploads.createFromFileOrBlob({
  fileOrBlob: fs.createReadStream(path),
  filename: 'image.jpg'
});

// 步骤2:在记录中使用上传的资产
await client.items.create({
  item_type: { type: 'item_type', id: 'blog_post' },
  title: 'Post with Image',
  cover_image: {
    upload_id: uploadRequest.id
  }
});

4. Migrations: Sandbox to Production

4. 迁移:沙箱到生产环境

When: Testing schema changes before deploying
bash
undefined
适用场景: 部署前测试架构变更
bash
undefined

Create sandbox environment

创建沙箱环境

(Do this in DatoCMS UI: Settings > Environments)

(在DatoCMS UI中操作:设置 > 环境)

Make changes in sandbox

在沙箱中进行变更

DATOCMS_ENVIRONMENT=sandbox node update-schema.js
DATOCMS_ENVIRONMENT=sandbox node update-schema.js

Test in sandbox

在沙箱中测试

Promote to primary environment (via UI or API)

推广到主环境(通过UI或API)

undefined
undefined

5. Structured Text (DAST): Handling Rich Content

5. 结构化文本(DAST):处理富文本内容

When: Working with rich text fields
typescript
import { render } from 'datocms-structured-text-to-html-string';

// DAST structure
const structuredText = {
  schema: 'dast',
  document: {
    type: 'root',
    children: [
      {
        type: 'heading',
        level: 1,
        children: [{ type: 'span', value: 'Hello World' }]
      },
      {
        type: 'paragraph',
        children: [
          { type: 'span', value: 'This is ' },
          { type: 'span', marks: ['strong'], value: 'bold text' }
        ]
      }
    ]
  }
};

// Render to HTML
const html = render(structuredText);
适用场景: 处理富文本字段
typescript
import { render } from 'datocms-structured-text-to-html-string';

// DAST结构
const structuredText = {
  schema: 'dast',
  document: {
    type: 'root',
    children: [
      {
        type: 'heading',
        level: 1,
        children: [{ type: 'span', value: 'Hello World' }]
      },
      {
        type: 'paragraph',
        children: [
          { type: 'span', value: 'This is ' },
          { type: 'span', marks: ['strong'], value: 'bold text' }
        ]
      }
    ]
  }
};

// 渲染为HTML
const html = render(structuredText);

6. Webhooks: Event Notifications

6. Webhooks:事件通知

When: Triggering builds or syncing data on content changes
typescript
// Create webhook via CMA
const webhook = await client.webhooks.create({
  name: 'Deploy on Publish',
  url: 'https://api.vercel.com/v1/integrations/deploy/...',
  events: [
    { entity_type: 'item', event_types: ['publish', 'unpublish'] }
  ],
  http_basic_user: 'user',
  http_basic_password: 'pass'
});
适用场景: 内容变更时触发构建或同步数据
typescript
// 通过CMA创建Webhook
const webhook = await client.webhooks.create({
  name: 'Deploy on Publish',
  url: 'https://api.vercel.com/v1/integrations/deploy/...',
  events: [
    { entity_type: 'item', event_types: ['publish', 'unpublish'] }
  ],
  http_basic_user: 'user',
  http_basic_password: 'pass'
});

7. Framework Integration: Next.js Example

7. 框架集成:Next.js示例

When: Building a Next.js site with DatoCMS
typescript
// app/blog/page.tsx
import { executeQuery } from '@datocms/cda-client';

const query = `
  query {
    allBlogPosts(orderBy: publishedAt_DESC) {
      id
      title
      slug
      excerpt
    }
  }
`;

export default async function BlogPage() {
  const { allBlogPosts } = await executeQuery(query, {
    token: process.env.DATOCMS_API_TOKEN!
  });

  return (
    <div>
      {allBlogPosts.map(post => (
        <article key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.excerpt}</p>
        </article>
      ))}
    </div>
  );
}
适用场景: 使用DatoCMS构建Next.js站点
typescript
// app/blog/page.tsx
import { executeQuery } from '@datocms/cda-client';

const query = `
  query {
    allBlogPosts(orderBy: publishedAt_DESC) {
      id
      title
      slug
      excerpt
    }
  }
`;

export default async function BlogPage() {
  const { allBlogPosts } = await executeQuery(query, {
    token: process.env.DATOCMS_API_TOKEN!
  });

  return (
    <div>
      {allBlogPosts.map(post => (
        <article key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.excerpt}</p>
        </article>
      ))}
    </div>
  );
}

MCP Server Integration

MCP服务器集成

DatoCMS provides an official Model Context Protocol (MCP) server for AI agents:
DatoCMS为AI代理提供官方模型上下文协议(MCP)服务器:

Installation

安装

json
{
  "mcpServers": {
    "datocms": {
      "command": "npx",
      "args": ["-y", "@datocms/mcp-server"],
      "env": {
        "DATOCMS_API_TOKEN": "your-full-access-token"
      }
    }
  }
}
json
{
  "mcpServers": {
    "datocms": {
      "command": "npx",
      "args": ["-y", "@datocms/mcp-server"],
      "env": {
        "DATOCMS_API_TOKEN": "your-full-access-token"
      }
    }
  }
}

Available Tools

可用工具

  • list_models
    - List all content models
  • get_model
    - Get model details with fields
  • list_records
    - List records of a model
  • get_record
    - Get single record by ID
  • create_record
    - Create new record
  • update_record
    - Update existing record
  • delete_record
    - Delete record
  • list_models
    - 列出所有内容模型
  • get_model
    - 获取包含字段的模型详情
  • list_records
    - 列出某模型的所有记录
  • get_record
    - 通过ID获取单个记录
  • create_record
    - 创建新记录
  • update_record
    - 更新现有记录
  • delete_record
    - 删除记录

Troubleshooting

故障排除

Common Issues

常见问题

1. "Invalid API token"
  • Verify token in Settings > API Tokens
  • Check environment variable is loaded
  • Ensure token has required permissions (read-only vs full-access)
2. "Model/Field not found"
  • Use
    api_key
    not
    id
    in queries
  • Check model exists in current environment
  • Verify field spelling and case sensitivity
3. "Rate limit exceeded"
  • CDA: 30 requests/second (burst: 60)
  • CMA: 15 requests/second
  • Implement exponential backoff
4. Asset upload fails
  • Check file size limits (5GB max)
  • Verify file type is supported
  • Use
    createFromFileOrBlob
    method
5. Structured text not rendering
  • Validate DAST schema structure
  • Use official rendering packages
  • Check for custom block types
1. "无效API令牌"
  • 在“设置 > API令牌”中验证令牌
  • 检查环境变量是否已加载
  • 确保令牌拥有所需权限(只读 vs 全权限)
2. "未找到模型/字段"
  • 在查询中使用
    api_key
    而非
    id
  • 检查模型是否存在于当前环境
  • 验证字段拼写和大小写敏感性
3. "超出速率限制"
  • CDA:30请求/秒(突发:60)
  • CMA:15请求/秒
  • 实现指数退避策略
4. 资产上传失败
  • 检查文件大小限制(最大5GB)
  • 验证文件类型是否受支持
  • 使用
    createFromFileOrBlob
    方法
5. 结构化文本无法渲染
  • 验证DAST架构结构
  • 使用官方渲染包
  • 检查是否存在自定义块类型

Debug Checklist

调试清单

  • API token is correct and has required permissions
  • Environment name matches (main vs sandbox)
  • API key names match schema (not display names)
  • Request payload matches API documentation
  • Check DatoCMS status page for outages
  • Review API logs in DatoCMS settings
  • API令牌正确且拥有所需权限
  • 环境名称匹配(main vs sandbox)
  • API键名称与架构匹配(而非显示名称)
  • 请求负载符合API文档要求
  • 查看DatoCMS状态页面确认是否有服务中断
  • 查看DatoCMS设置中的API日志

Documentation Reference

文档参考

Below is the complete index of DatoCMS documentation organized by topic. All links point to Markdown versions for easy parsing.
以下是按主题整理的完整DatoCMS文档索引,所有链接指向Markdown版本以便于解析。

DatoCMS

DatoCMS

Docs

文档

Official packages READMEs

官方包README