designing-zod-schemas
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseZod Schema Designer
Zod Schema 设计指南
Overview
概述
Guide the design and implementation of Zod schemas following the project's Zod-first development approach, where schemas are defined before implementing business logic.
本指南遵循项目的Zod优先开发方法,指导Zod Schema的设计与实现,即先定义Schema,再实现业务逻辑。
When to Use
适用场景
- Creating new data structures
- Adding validation to inputs
- Designing configuration schemas
- Implementing type-safe transformations
- Creating test data builders
- 创建新的数据结构
- 为输入添加验证
- 设计配置Schema
- 实现类型安全的转换
- 创建测试数据生成器
Core Principles
核心原则
Zod-First Development
Zod优先开发
- Define Schema First: Schema is the source of truth
- Infer Types: Use instead of manual type definitions
z.infer<> - Share Validation: Same schema for runtime validation and tests
- Compose Schemas: Build complex schemas from primitives
- 先定义Schema:Schema是唯一可信来源
- 推导类型:使用而非手动定义类型
z.infer<> - 共享验证逻辑:同一Schema用于运行时验证和测试
- 组合Schema:基于基础类型构建复杂Schema
Decision Guide
决策指南
| Need | Pattern | Example |
|---|---|---|
| Basic validation | Primitives | |
| Domain safety | Branded types | |
| Multiple types | Discriminated union | |
| Cross-field rules | Refinement | |
| Data normalization | Transform | |
| Partial updates | Partial schema | |
| 需求 | 模式 | 示例 |
|---|---|---|
| 基础验证 | Primitives | |
| 领域安全性 | Branded Types | |
| 多类型场景 | Discriminated Union | |
| 跨字段规则 | Refinement | |
| 数据标准化 | Transform | |
| 部分更新 | Partial Schema | |
Quick Reference
快速参考
Project Schema Conventions
项目Schema约定
typescript
import { z } from 'zod';
// Slug-based entity (Categories, Products, Channels, etc.)
const SlugSchema = z.string().regex(/^[a-z0-9-]+$/);
// Name-based entity (ProductTypes, Attributes, TaxClasses, etc.)
const NameSchema = z.string().min(1).max(100).trim();
// Branded types for domain safety
const EntitySlugSchema = SlugSchema.transform((v) => v as EntitySlug);
// Standard entity shape
const EntitySchema = z.object({
name: z.string().min(1),
slug: z.string().regex(/^[a-z0-9-]+$/),
description: z.string().optional(),
});
// Always infer types from schemas
type Entity = z.infer<typeof EntitySchema>;typescript
import { z } from 'zod';
// Slug-based entity (Categories, Products, Channels, etc.)
const SlugSchema = z.string().regex(/^[a-z0-9-]+$/);
// Name-based entity (ProductTypes, Attributes, TaxClasses, etc.)
const NameSchema = z.string().min(1).max(100).trim();
// Branded types for domain safety
const EntitySlugSchema = SlugSchema.transform((v) => v as EntitySlug);
// Standard entity shape
const EntitySchema = z.object({
name: z.string().min(1),
slug: z.string().regex(/^[a-z0-9-]+$/),
description: z.string().optional(),
});
// Always infer types from schemas
type Entity = z.infer<typeof EntitySchema>;Schema Patterns
Schema模式
For detailed patterns and examples, see:
- Primitive Patterns: Strings, numbers, enums, branded types
- Object Patterns: Objects, discriminated unions, arrays, transforms, refinements
- Testing Patterns: Test data builders, schema validation tests
如需详细的模式和示例,请查看:
- 基础类型模式:字符串、数字、枚举、branded types
- 对象模式:对象、discriminated unions、数组、转换、细化规则
- 测试模式:测试数据生成器、Schema验证测试
Project Schema Location
项目Schema存放位置
src/modules/config/schema/
├── schema.ts # Main configuration schema
├── primitives.ts # Reusable primitive schemas
├── entities/ # Entity-specific schemas
│ ├── category.ts
│ ├── product.ts
│ └── ...
└── index.ts # Schema exportssrc/modules/config/schema/
├── schema.ts # 主Schema定义
├── primitives.ts # 可复用的基础Schema
├── entities/ # 实体专属Schema
│ ├── category.ts
│ ├── product.ts
│ └── ...
└── index.ts # Schema导出文件Validation Checkpoints
验证检查点
| Phase | Validate | Command |
|---|---|---|
| Schema defined | No TS errors | |
| Types inferred | | Check type in IDE |
| Validation works | | |
| 阶段 | 验证内容 | 命令 |
|---|---|---|
| Schema已定义 | 无TypeScript错误 | |
| 类型已推导 | | 在IDE中检查类型 |
| 验证功能正常 | | |
Common Mistakes
常见错误
| Mistake | Issue | Fix |
|---|---|---|
| Manual type definitions | Type drift | Use |
Using | Throws on invalid | Use |
Missing | Runtime errors | Mark optional fields explicitly |
| Complex refinements | Hard to debug | Break into smaller schemas |
| Not using branded types | Type confusion | Use |
| 错误行为 | 问题 | 修复方案 |
|---|---|---|
| 手动定义类型 | 类型漂移 | 使用 |
直接使用 | 无效数据时抛出异常 | 使用 |
遗漏 | 运行时错误 | 显式标记可选字段 |
| 复杂的细化规则 | 难以调试 | 拆分为更小的Schema |
| 未使用branded types | 类型混淆 | 使用 |
External Documentation
外部文档
For up-to-date Zod patterns, use Context7 MCP:
mcp__context7__get-library-docs with context7CompatibleLibraryID: "/colinhacks/zod"如需最新的Zod模式,请使用Context7 MCP:
mcp__context7__get-library-docs with context7CompatibleLibraryID: "/colinhacks/zod"References
参考资料
- - Main schema definitions
{baseDir}/src/modules/config/schema/schema.ts - - Quality standards
{baseDir}/docs/CODE_QUALITY.md#zod-first-development - Zod documentation: https://zod.dev
- - 主Schema定义
{baseDir}/src/modules/config/schema/schema.ts - - 质量标准
{baseDir}/docs/CODE_QUALITY.md#zod-first-development - Zod官方文档:https://zod.dev
Related Skills
相关技能
- Complete entity workflow: See for full schema-to-service implementation
adding-entity-types - Testing schemas: See for test data builders
analyzing-test-coverage - GraphQL type mapping: See for schema-to-GraphQL patterns
writing-graphql-operations
- 完整实体工作流:查看了解从Schema到服务的完整实现
adding-entity-types - Schema测试:查看了解测试数据生成器
analyzing-test-coverage - GraphQL类型映射:查看了解Schema到GraphQL的映射模式
writing-graphql-operations
Quick Reference Rule
快速参考规则
For a condensed quick reference, see (automatically loaded when editing files).
.claude/rules/config-schema.mdsrc/modules/config/**/*.ts如需简洁的快速参考,请查看(编辑文件时会自动加载)。
.claude/rules/config-schema.mdsrc/modules/config/**/*.ts