Agent Skillsmx-space/core › zod-patterns

zod-patterns

GitHub

提供 NestJS 项目中基于 Zod 的 DTO 创建、数据校验及自定义验证器使用模式,涵盖基础定义、实体 ID 校验及字段扩展等规范。

.claude/skills/zod-patterns/SKILL.md mx-space/core

Trigger Scenarios

创建 DTO 类 编写数据校验 Schema 处理请求参数验证

Install

npx skills add mx-space/core --skill zod-patterns -g -y
More Options

Non-standard path

npx skills add https://github.com/mx-space/core/tree/master/.claude/skills/zod-patterns -g -y

Use without installing

npx skills use mx-space/core@zod-patterns

指定 Agent (Claude Code)

npx skills add mx-space/core --skill zod-patterns -a claude-code -g -y

安装 repo 全部 skill

npx skills add mx-space/core --all -g -y

预览 repo 内 skill

npx skills add mx-space/core --list

SKILL.md

Frontmatter
{
    "name": "zod-patterns",
    "description": "Mix Space project Zod schema patterns. Apply when creating DTOs, validation schemas, or handling request validation.",
    "user-invocable": false
}

Zod Schema Patterns

Basic Pattern

import { z } from 'zod'
import { createZodDto } from 'nestjs-zod'

// Define Schema
export const MySchema = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  age: z.number().int().positive().optional(),
})

// Create DTO class
export class MyDto extends createZodDto(MySchema) {}

// Partial DTO for updates
export class PartialMyDto extends createZodDto(MySchema.partial()) {}

Project Custom Validators

Location: apps/core/src/common/zod/

import {
  // From primitives.ts:
  zNonEmptyString, // Non-empty string (z.string().min(1))
  zCoerceInt, // Coerced integer
  zCoercePositiveInt, // Coerced positive integer
  zCoerceBoolean, // Coerced boolean (handles 'true'/'1'/1/etc.)
  zCoerceDate, // Coerced date
  zOptionalDate, // Optional date (null/empty → undefined)
  zOptionalBoolean, // Optional coerced boolean
  zEmptyStringToNull, // Empty string → null, else string
  zNilOrString, // string | null | undefined
  zHexColor, // Hex color (#fff or #ffffff)
  zAllowedUrl, // HTTP or HTTPS URL
  zStrictUrl, // Strict URL validation
  zHttpsUrl, // HTTPS-only URL
  zPaginationPage, // Coerced int, min 1, default 1
  zPaginationSize, // Coerced int, min 1, max 50, default 20
  zSortOrder, // 1 | -1 | undefined (accepts 'asc'/'desc')
  zArrayUnique, // Unique array elements (generic)
  zUniqueStringArray, // Unique non-empty string array

  // From custom.ts:
  zBooleanOrString, // boolean | string union
  zTransformEmptyNull, // Empty string → null (generic wrapper)
  zTransformBoolean, // Transform to optional boolean
  zPinDate, // Pin date (Date | null | undefined, true=now, false=null)
  zSlug, // Slug string (trimmed)
  zEmail, // Email with custom message
  zUrl, // URL with custom message
  zMaxLengthString, // Max length string factory
  zRefTypeTransform, // Content ref type ('post'→'Post', etc.)
  zPrefer, // 'lexical' enum optional
  zLang, // 2-char language code

  // From shared/id/entity-id.ts:
  zEntityId, // Snowflake entity ID string validation
  zEntityIdOrInt, // Entity ID or positive integer union
} from '~/common/zod'

Entity ID Validation

import { zEntityId } from '~/common/zod'

const Schema = z.object({
  id: zEntityId, // Snowflake ID string
  categoryId: zEntityId, // Foreign key reference
  relatedIds: z.array(zEntityId), // Array of entity IDs
})

// For DTOs used in path params:
import { EntityIdDto } from '~/shared/dto/id.dto'
// EntityIdDto = { id: zEntityId }

Extending Base Schemas

// Compose schemas using .extend()
const PostSchema = z.object({
  title: zNonEmptyString,
  slug: zSlug,
  categoryId: zEntityId,
  tags: z.array(z.string()).optional(),
  contentFormat: z.enum(['markdown', 'lexical']),
})

Common Patterns

Optional Fields with Defaults

z.boolean().default(true).optional()
z.number().default(0).optional()
z.array(z.string()).default([]).optional()

Preprocessing

// Empty string to null
z.preprocess(
  (val) => (val === '' ? null : val),
  z.string().nullable(),
).optional()

// String to number
z.preprocess(
  (val) => (typeof val === 'string' ? parseInt(val, 10) : val),
  z.number(),
)

Union Types

z.union([z.string(), z.number()])
z.enum(['draft', 'published', 'archived'])

Array Validation

// Basic array
z.array(z.string())

// Length constraints
z.array(z.string()).min(1).max(10)

// Unique elements
zArrayUnique(z.string())

Nested Objects

const AddressSchema = z.object({
  street: z.string(),
  city: z.string(),
})

const UserSchema = z.object({
  name: z.string(),
  address: AddressSchema.optional(),
  addresses: z.array(AddressSchema).optional(),
})

Conditional Validation

// refine for custom validation
z.object({
  password: z.string(),
  confirmPassword: z.string(),
}).refine((data) => data.password === data.confirmPassword, {
  message: 'Passwords must match',
})

Type Inference

// Infer type from Schema
type MyType = z.infer<typeof MySchema>

// Use in Service
async create(data: z.infer<typeof MySchema>) {
  return this.repository.create(data)
}

Version History

  • 121b820 Current 2026-08-28 10:11

    修正项目文档中的项目名称引用,从 MX Space 统一更新为 Mix Space。

  • a28bdf5 2026-07-25 05:38

Same Skill Collection

.claude/skills/api-conventions/SKILL.md
.claude/skills/create-e2e-test/SKILL.md
.claude/skills/create-module/SKILL.md
.claude/skills/mx-core-local-auth/SKILL.md
.claude/skills/mx-pg-controller-migration/SKILL.md
.claude/skills/mx-review/SKILL.md
.claude/skills/mxs-cli-ai-author/SKILL.md
.claude/skills/release-core/SKILL.md
.claude/skills/run-test/SKILL.md
.claude/skills/mx-migration-author/SKILL.md

Metadata

Files
0
Version
121b820
Hash
477692a5
Indexed
2026-07-25 05:38

trang chủ - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-09-01 20:45
浙ICP备14020137号-1 $bản đồ khách truy cập$