@beparallel/zod-to-dto
v0.0.15
Published
CLI to convert Zod schemas to NestJS-compatible DTOs with Swagger and class-validator decorators
Readme
zod-to-dto
A powerful CLI tool that automatically converts Zod schemas to NestJS-compatible DTOs with Swagger documentation and class-validator decorators.
Features
- 🔄 Automatic Conversion: Transform Zod schemas into NestJS DTOs
- 📚 Swagger Integration: Generates
@ApiPropertydecorators for OpenAPI documentation - ✅ Validation Ready: Includes class-validator decorators (
@IsString,@IsNumber, etc.) - 🎯 Type Safe: Maintains TypeScript type safety throughout the conversion
- 📁 Batch Processing: Process multiple schema files at once using glob patterns
- 🎨 Customizable: Configurable input and output paths
Installation
Global Installation (Recommended)
npm install -g zod-to-dtoLocal Installation
npm install --save-dev zod-to-dto
# or
yarn add --dev zod-to-dto
# or
pnpm add -D zod-to-dtoRequirements
- Node.js >= 18.0.0
- TypeScript project with Zod schemas
Quick Start
- Create your Zod schemas (e.g.,
src/schemas/user.schema.ts):
import { z } from 'zod';
export const UserSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email(),
age: z.number().optional(),
isActive: z.boolean(),
tags: z.array(z.string()),
createdAt: z.date(),
});
export const ProductSchema = z.object({
id: z.number(),
title: z.string(),
description: z.string().optional(),
price: z.number(),
categories: z.array(z.string()),
inStock: z.boolean(),
});- Run the CLI tool:
zod-to-dtoThis will generate NestJS DTOs in the src/generated/dtos directory.
Usage
Basic Usage
zod-to-dtoUses default settings:
- Input:
src/**/*.zod.ts(searches for files ending with.zod.ts) - Output:
src/generated/dtos/directory
Custom Input/Output Paths
zod-to-dto -i "src/schemas/*.ts" -o "src/generated"CLI Options
| Option | Alias | Description | Default |
| ---------- | ----- | ----------------------------------- | -------------------- |
| --input | -i | Glob pattern for Zod schema files | src/**/*.zod.ts |
| --output | -o | Output directory for generated DTOs | src/generated/dtos |
| --help | -h | Show help information | - |
Examples
# Process all TypeScript files in src/schemas
zod-to-dto -i "src/schemas/*.ts" -o "src/dtos"
# Process files with specific naming pattern
zod-to-dto -i "**/*.schema.ts" -o "generated"
# Process files in multiple directories
zod-to-dto -i "src/{models,schemas}/*.ts" -o "dist/dtos"Generated Output
Input Schema
// src/schemas/user.schema.ts
import { z } from 'zod';
export const UserSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email(),
age: z.number().optional(),
isActive: z.boolean(),
tags: z.array(z.string()),
createdAt: z.date(),
});Generated DTO
// src/generated/dtos/user.dto.ts
import { ApiProperty } from '@nestjs/swagger';
import {
IsString,
IsNumber,
IsBoolean,
IsOptional,
IsDate,
} from 'class-validator';
export class UserDto {
@ApiProperty()
@IsString()
id: string;
@ApiProperty()
@IsString()
name: string;
@ApiProperty()
@IsString()
email: string;
@ApiProperty({ required: false })
@IsNumber()
@IsOptional()
age?: number;
@ApiProperty()
@IsBoolean()
isActive: boolean;
@ApiProperty({ isArray: true })
@IsString()
tags: string[];
@ApiProperty()
@IsDate()
createdAt: Date;
}Supported Zod Types
| Zod Type | TypeScript Type | class-validator Decorator |
| ---------------- | --------------- | --------------------------------------- |
| z.string() | string | @IsString() |
| z.number() | number | @IsNumber() |
| z.boolean() | boolean | @IsBoolean() |
| z.date() | Date | @IsDate() |
| z.array(T) | T[] | Appropriate decorator + isArray: true |
| z.*.optional() | T? | @IsOptional() |
| Custom/Unknown | any | @IsOptional() |
Integration with NestJS
The generated DTOs are ready to use in your NestJS controllers:
import { Controller, Post, Body } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { UserDto } from './src/generated/dtos/user.dto';
@ApiTags('users')
@Controller('users')
export class UsersController {
@Post()
@ApiOperation({ summary: 'Create a new user' })
async createUser(@Body() createUserDto: UserDto) {
// The DTO is automatically validated and documented
return this.usersService.create(createUserDto);
}
}Package.json Scripts
Add these scripts to your package.json for easier usage:
{
"scripts": {
"generate:dtos": "zod-to-dto",
"generate:dtos:watch": "nodemon --exec \"zod-to-dto\" --watch src --ext ts",
"build": "zod-to-dto && tsc"
}
}Then run with:
npm run generate:dtosFile Naming Conventions
- Input files: The tool looks for exported Zod schemas in your TypeScript files
- Output files: Generated DTOs follow the pattern
{schemaname}.dto.tsUserSchema→user.dto.tsProductSchema→product.dto.tsOrderSchema→order.dto.ts
Tips and Best Practices
Consistent Naming: Use the suffix
Schemafor your Zod schemas (e.g.,UserSchema,ProductSchema)File Organization: Keep your schemas in dedicated directories for easier glob pattern matching
Validation: The generated DTOs include both Swagger documentation and validation decorators
Type Safety: Import and use the generated DTOs in your NestJS controllers for full type safety
Build Process: Consider adding DTO generation to your build pipeline
Troubleshooting
Common Issues
Issue: No files found
# Make sure your glob pattern matches your file structure
zod-to-dto -i "src/**/*.schema.ts"Issue: Missing decorators in output
- Ensure your Zod schemas use supported types
- Check that schemas are properly exported with
export const
Issue: TypeScript compilation errors
- Make sure you have the required dependencies installed:
npm install @nestjs/swagger class-validator class-transformer
Debug Mode
Enable verbose logging by setting the environment variable:
DEBUG=zod-to-dto zod-to-dtoContributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Dependencies
- commander - Command-line interfaces
- fast-glob - File globbing
- ts-morph - TypeScript compiler API wrapper
- zod - TypeScript-first schema validation
Related Projects
- Zod - TypeScript-first schema validation
- NestJS - Progressive Node.js framework
- class-validator - Validation decorators
- Swagger/OpenAPI - API documentation
Made with ❤️ for the NestJS and TypeScript community
