关于模式的文章
该功能允许您以类型安全的 Zod 模式获取组件描述,提供:
了解更多:https://zod.dev
要获取 Zod 模式,您需要:
cms-renderer 中的工具创建脚本apps/
web/
app/
page.tsx
scripts/
generated-schema.ts # 脚本文件
generated-schema.tsimport { fetchAllCustomSchemaFields, saveZodSchemaCode } from 'cms-renderer/lib/custom-schemas';
import { cmsConfig } from '../lib/cms-config';
async function main() {
const { cmsUrl, websiteId, apiKey } = cmsConfig;
if (!cmsUrl) {
throw new Error(
'[generate-schemas] NEXT_PUBLIC_CMS_API_URL 未设置。请在环境或 .env 文件中进行设置。'
);
}
if (!websiteId) {
throw new Error(
'[generate-schemas] CMS_WEBSITE_ID 未设置。请在环境或 .env 文件中进行设置。'
);
}
if (!apiKey) {
throw new Error(
'[generate-schemas] PROFOUND_API_KEY 未设置。请在环境或 .env 文件中进行设置。'
);
}
const schemas = await fetchAllCustomSchemaFields({ cmsUrl, websiteId, apiKey });
if (schemas.length === 0) {
throw new Error(
'[generate-schemas] API 未返回任何组件。请检查 PROFOUND_API_KEY 是否有效并指向正确的网站。'
);
}
console.log(
`[generate-schemas] 找到 ${schemas.length} 个组件:${schemas.map((s) => s.name).join(', ')}`
);
await saveZodSchemaCode(schemas, './generated/cms-schemas.ts');
console.log('[generate-schemas] 完成。');
}
main().catch((err) => {
console.error('[generate-schemas] 失败:', err);
process.exit(1);
});
export const cmsConfig = {
cmsUrl: process.env.NEXT_PUBLIC_CMS_API_URL,
apiKey: process.env.CMS_API_KEY,
websiteId: '...',
};
package.json 配置注意:如果您没有
tsconfig.json,请移除--tsconfig标志。
{
"name": "web",
"version": "0.1.0",
"type": "module",
"private": true,
"scripts": {
"generate-schemas": "tsx --tsconfig tsconfig.json scripts/generate-schemas.ts",
"...": "..."
},
"dependencies": {
"cms-renderer": "0.3.1",
"zod": "^4.3.6",
"...": "..."
},
"devDependencies": {
"tsx": "^4.21.0",
"object-hash": "^3.0.0",
"...": "..."
}
}
bun run generate-schemas
示例输出:
tsx --tsconfig tsconfig.json scripts/generate-schemas.ts
[generate-schemas] 找到 3 个组件:post, categories, header
[generate-schemas] 完成。
apps/
web/
app/
page.tsx
scripts/
generated-schema.ts
generated/
cms-schemas.ts # 生成的 Zod 模式
page.tsx 中使用import type { PetFoodPost, SiteConfig } from '@/generated/cms-schemas';
import { petFoodPostSchema } from '@/generated/cms-schemas';
// 用于类型安全的解析
petFoodPostSchema.parse(obj);
bun run generate-schemas