@scvzerng/zod-to-class
v0.0.2
Published
一个将 Zod schema 转换为 TypeScript 类的工具,支持自动注册和类型转换。
Downloads
5
Readme
Zod to Class Converter
一个将 Zod schema 转换为 TypeScript 类的工具,支持自动注册和类型转换。
特性
- 自动生成 TypeScript 类定义
- 自动注册 Zod schema 和类之间的映射关系
- 支持嵌套对象、数组、记录等复杂类型
- 支持循环引用结构
- 简单易用的 API
- 命令行工具支持
安装
npm install @scvzerng/zod-to-class使用方法
1. 定义 Zod Schema
import { z } from 'zod';
// 支持循环引用的 Address Schema
const AddressSchema = z.object({
street: z.string(),
city: z.string(),
zipCode: z.string(),
get parent() {
return AddressSchema.optional();
}
});
const UserSchema = z.object({
id: z.string(),
name: z.string(),
age: z.number(),
email: z.string().optional(),
address: AddressSchema.optional()
});2. 自动生成类定义
运行命令自动生成类文件:
# 扫描默认的 __tests__ 目录
npm run gen:classes
# 扫描指定目录
npm run gen:classes your/schema/directory
# 扫描多个目录
npm run gen:classes directory1 directory23. 作为命令行工具使用(构建后)
构建项目后,可以作为命令行工具使用:
# 全局安装后使用
npm install -g @scvzerng/zod-to-class
zod-to-class path/to/schemas
# 或者使用 npx
npx @scvzerng/zod-to-class path/to/schemas4. 使用自定义 CLI 脚本
你也可以将 CLI 文件放在自己的 bin 目录中:
# 构建项目
npm run build
# 复制 CLI 文件到你的 bin 目录
cp bin/zod-to-class.js /path/to/your/bin/
# 使用
/path/to/your/bin/zod-to-class.js path/to/schemas5. 使用 zodToClass 转换数据
import { zodToClass } from '@scvzerng/zod-to-class';
import { User } from './user/_schema';
const userData = {
id: 'user-001',
name: '张三',
age: 28,
email: '[email protected]'
};
const user = zodToClass(userData, User);
console.log(user instanceof User); // trueAPI
zodToClass(data, targetClass)
将原始数据转换为目标类的实例。
data: 原始数据对象targetClass: 目标类的构造函数
SchemaRegistry
管理类和 schema 之间映射关系的单例注册表。
通常不需要直接使用,除非需要手动注册额外的映射关系。
CLI 使用
CLI 工具会扫描指定目录(默认为当前工作目录)下的所有 .schema.ts 文件,并为每个 schema 生成对应的 TypeScript 类文件。
命令行参数
- 无参数:扫描当前工作目录
- 一个或多个路径:扫描指定的一个或多个目录
生成的文件
- 每个 schema 会生成一个对应的类文件
- 自动生成
index.ts文件,包含所有类的导出和 schema 的自动注册
构建
npm run build