@datocms/cma-schema-types-generator
由 DatoCMS 项目 schema 生成 TypeScript 类型定义 .
生产 ItemTypeDefinition- 基于类型(每个模型/块一个)加
AnyBlock 编号 : AnyModel 编号 : AnyBlockOrModel 工会类型,准备
用过的 @datocms/cma-client 用于类型安全的内容管理
迁移脚本.
安装
npm install @datocms/cma-schema-types-generator
@datocms/cma-client 是同级依赖.
使用量
import { buildClient } from '@datocms/cma-client';
import { generateSchemaTypes } from '@datocms/cma-schema-types-generator';
const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN! });
const code = await generateSchemaTypes(client);
code 是一个包含更美格式类型脚本的字符串,准备
写入磁盘 :
import { writeFile } from 'node:fs/promises';
await writeFile('src/generated/schema.ts', code);
示例输出
import type { ItemTypeDefinition } from '@datocms/cma-client';
type EnvironmentSettings = {
locales: 'en' | 'it';
};
export type BlogPost = ItemTypeDefinition<
EnvironmentSettings,
'12345',
{
title: { type: 'string'; localized: true };
content: { type: 'rich_text'; blocks: Hero };
}
>;
export const BlogPost = {
ID: '12345',
REF: { type: 'item_type', id: '12345' },
} as const;
export type Hero = ItemTypeDefinition<EnvironmentSettings, '67890', { /* … */ }>;
export const Hero = {
ID: '67890',
REF: { type: 'item_type', id: '67890' },
} as const;
export type AnyBlock = Hero;
export type AnyModel = BlogPost;
export type AnyBlockOrModel = AnyBlock | AnyModel;
类型和价值声明合并
每个项目类型都会被排放 两次: 一次作为类型脚本 type (单位:千美元)
ItemTypeDefinition<…> (别名)和一次作为 export const 携带
它的运行时间元数据。 TypeScript 合并了两者 —— Schema.BlogPost
以类型和值解决,取决于其位置
用于.
运行时会显示两个字段:
ID——赤项型号为id(如.'12345',键入为字符串 字面上可以用来缩小.REF—— JSON: API 资源标识对象{ type: 'item_type', id: '<sameId>' },准备通过任何地方 aPI 需要一个项目类型的引用.
这样可以调用站点保持没有硬码字符串 ID :
import { buildClient } from '@datocms/cma-client';
import * as Schema from './generated/schema';
const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN! });
await client.items.create<Schema.LandingPage>({
item_type: Schema.LandingPage.REF,
title: 'Hello world',
});
if (block.__itemTypeId === Schema.HeroBlock.ID) {
// narrowed to Schema.HeroBlock
}
选项
两个切入点都接受可选 SchemaTypesGeneratorOptions
对象 :
itemTypesFilter—— 逗号分隔的模型 api 密钥列表 内容包括: 保留模型(通过rich_text, (中文(简体) ),structured_text, (中文(简体) ),single_block) 被拖入时 自动。 未知的 api 密钥被忽略 .format——以 Pretier 为输出格式。 默认为true。 。 。 . Pretier 运行在工人的线程中,其记忆不会回到 主要过程:在一个有上千个字段的项目上,这增加了数百个字段 到顶峰内存使用量的兆字节。 准备吧false当代码 转到编译器,而不是一个人。 类型脚本打印机已经 输出缩进多行代码; 只有引号样式和行 休息时间不同.
移徙变式
generateSchemaTypesForMigration 作出同样的声明
无 页:1 import type { ItemTypeDefinition } ——原意为
直接插入已访问的迁移脚本
类型.
import { generateSchemaTypesForMigration } from '@datocms/cma-schema-types-generator';
const inline = await generateSchemaTypesForMigration(client, {
itemTypesFilter: 'blog_post,author',
});