npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@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

npm version License: MIT

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 @ApiProperty decorators 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-dto

Local Installation

npm install --save-dev zod-to-dto
# or
yarn add --dev zod-to-dto
# or
pnpm add -D zod-to-dto

Requirements

  • Node.js >= 18.0.0
  • TypeScript project with Zod schemas

Quick Start

  1. 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(),
});
  1. Run the CLI tool:
zod-to-dto

This will generate NestJS DTOs in the src/generated/dtos directory.

Usage

Basic Usage

zod-to-dto

Uses 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:dtos

File Naming Conventions

  • Input files: The tool looks for exported Zod schemas in your TypeScript files
  • Output files: Generated DTOs follow the pattern {schemaname}.dto.ts
    • UserSchemauser.dto.ts
    • ProductSchemaproduct.dto.ts
    • OrderSchemaorder.dto.ts

Tips and Best Practices

  1. Consistent Naming: Use the suffix Schema for your Zod schemas (e.g., UserSchema, ProductSchema)

  2. File Organization: Keep your schemas in dedicated directories for easier glob pattern matching

  3. Validation: The generated DTOs include both Swagger documentation and validation decorators

  4. Type Safety: Import and use the generated DTOs in your NestJS controllers for full type safety

  5. 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-dto

Contributing

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

Related Projects


Made with ❤️ for the NestJS and TypeScript community