zod 代码验证
- 作者仓库星标 529
- 许可证 NOASSERTION
- 作者仓库 core
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)
}- 流狐分类
- 通用
- 作者声明 Agent
- 未找到明确声明;不据此推断已兼容或已测试
- 静态检查
- 94 / 100 · 启发式扫描,不代表运行安全
- 作者 / 版本 / 许可
- @mx-space · NOASSERTION
- 流狐 Token 估算
- 低消耗
- 流狐接入估算
- 即装即用
- 是否需要外部 API Key
- 未发现要求
- 检测到的系统要求
- 未声明
- 底层运行要求
- 未声明
- 检测到的文件与系统行为
-
- 只读
- 允许写入 / 修改
- 检测到的网络行为
- 仅限本地
- 安装命令数
- 无(仅作为资料)
档案由构建时根据 SKILL.md 与安装命令自动衍生,可能与作者实际意图存在差异。
需要注意: 未限定 allowed-tools,默认拥有全部工具权限。
作者没有在当前 SKILL.md 中定义固定输出样例。 Basic Pattern
Basic Pattern
Project Custom Validators
Location: apps/core/src/common/zod/
Entity ID Validation
Entity ID Validation
Extending Base Schemas
Extending Base Schemas
Common Patterns
Common Patterns
Optional Fields with Defaults
Optional Fields with Defaults
# Zod Schema Patterns
## Basic Pattern
```typescript
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/`
```typescript
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
… 证据边界与执行链路
作者原文负责流程事实;流狐只索引当前章节、要点、文件与命令。
章节 -> Basic Pattern → Project Custom Validators → Entity ID Validation → Extending Base Schemas → Common Patterns → Optional Fields with Defaults
要点 -> // String to number z.preprocess( (val) => (typeof val === 'string' ?
文件/命令 -> apps/core/src/common/zod/ · apps/core/src/common/zod · primitives.ts · 1/etc. · null/empty · custom.ts · shared/id/entity-id.ts · common/zod
内容 SHA-256 -> 0f5abd98cfd3
方法与流程
适用与边界
原文中的明确线索
apps/core/src/common/zod/、apps/core/src/common/zod、primitives.ts、1/etc.、null/empty、custom.ts、shared/id/entity-id.ts、common/zod