designing-zod-schemas

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Zod 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优先开发

  1. Define Schema First: Schema is the source of truth
  2. Infer Types: Use
    z.infer<>
    instead of manual type definitions
  3. Share Validation: Same schema for runtime validation and tests
  4. Compose Schemas: Build complex schemas from primitives
  1. 先定义Schema:Schema是唯一可信来源
  2. 推导类型:使用
    z.infer<>
    而非手动定义类型
  3. 共享验证逻辑:同一Schema用于运行时验证和测试
  4. 组合Schema:基于基础类型构建复杂Schema

Decision Guide

决策指南

NeedPatternExample
Basic validationPrimitives
z.string().min(1)
Domain safetyBranded types
transform((v) => v as EntitySlug)
Multiple typesDiscriminated union
z.discriminatedUnion('type', [...])
Cross-field rulesRefinement
.refine((data) => ...)
Data normalizationTransform
.transform((v) => v.trim())
Partial updatesPartial schema
Schema.partial()
需求模式示例
基础验证Primitives
z.string().min(1)
领域安全性Branded Types
transform((v) => v as EntitySlug)
多类型场景Discriminated Union
z.discriminatedUnion('type', [...])
跨字段规则Refinement
.refine((data) => ...)
数据标准化Transform
.transform((v) => v.trim())
部分更新Partial Schema
Schema.partial()

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 exports
src/modules/config/schema/
├── schema.ts           # 主Schema定义
├── primitives.ts       # 可复用的基础Schema
├── entities/           # 实体专属Schema
│   ├── category.ts
│   ├── product.ts
│   └── ...
└── index.ts            # Schema导出文件

Validation Checkpoints

验证检查点

PhaseValidateCommand
Schema definedNo TS errors
npx tsc --noEmit
Types inferred
z.infer
works
Check type in IDE
Validation works
safeParse
tests
pnpm test
阶段验证内容命令
Schema已定义无TypeScript错误
npx tsc --noEmit
类型已推导
z.infer
功能正常
在IDE中检查类型
验证功能正常
safeParse
测试通过
pnpm test

Common Mistakes

常见错误

MistakeIssueFix
Manual type definitionsType driftUse
z.infer<typeof Schema>
Using
.parse()
directly
Throws on invalidUse
.safeParse()
for error handling
Missing
.optional()
Runtime errorsMark optional fields explicitly
Complex refinementsHard to debugBreak into smaller schemas
Not using branded typesType confusionUse
.brand()
or transform for domain safety
错误行为问题修复方案
手动定义类型类型漂移使用
z.infer<typeof Schema>
直接使用
.parse()
无效数据时抛出异常使用
.safeParse()
进行错误处理
遗漏
.optional()
运行时错误显式标记可选字段
复杂的细化规则难以调试拆分为更小的Schema
未使用branded types类型混淆使用
.brand()
或转换来保证领域安全性

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

参考资料

  • {baseDir}/src/modules/config/schema/schema.ts
    - Main schema definitions
  • {baseDir}/docs/CODE_QUALITY.md#zod-first-development
    - Quality standards
  • Zod documentation: https://zod.dev
  • {baseDir}/src/modules/config/schema/schema.ts
    - 主Schema定义
  • {baseDir}/docs/CODE_QUALITY.md#zod-first-development
    - 质量标准
  • Zod官方文档:https://zod.dev

Related Skills

相关技能

  • Complete entity workflow: See
    adding-entity-types
    for full schema-to-service implementation
  • Testing schemas: See
    analyzing-test-coverage
    for test data builders
  • GraphQL type mapping: See
    writing-graphql-operations
    for schema-to-GraphQL patterns
  • 完整实体工作流:查看
    adding-entity-types
    了解从Schema到服务的完整实现
  • Schema测试:查看
    analyzing-test-coverage
    了解测试数据生成器
  • GraphQL类型映射:查看
    writing-graphql-operations
    了解Schema到GraphQL的映射模式

Quick Reference Rule

快速参考规则

For a condensed quick reference, see
.claude/rules/config-schema.md
(automatically loaded when editing
src/modules/config/**/*.ts
files).
如需简洁的快速参考,请查看
.claude/rules/config-schema.md
(编辑
src/modules/config/**/*.ts
文件时会自动加载)。