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

tsoa-zod-validator

v0.1.0

Published

Zod validation decorators for tsoa

Readme

tsoa-zod-validator

A powerful TypeScript library extending tsoa's validation capabilities with Zod schema validation. This library provides type-safe validation with an excellent developer experience.

Installation

# Using npm
npm install tsoa-zod-validator

# Using yarn
yarn add tsoa-zod-validator

# Using pnpm
pnpm add tsoa-zod-validator

Core Value Propositions

Type Safety

The library provides complete type inference when using Zod schemas for validation:

import { z } from 'zod';
import { ZodValidate } from 'tsoa-zod-validator';

const UserSchema = z.object({
  name: z.string().min(2),
  email: z.string().email(),
  age: z.number().min(18).optional()
});

@ZodValidate({ body: UserSchema })
public async createUser(@Body() userData: z.infer<typeof UserSchema>) {
  // userData has complete type inference
  // No need for manual type assertions
}

Multiple Validation Targets

The library supports validating different parts of the request:

  • Body validation: POST/PUT request bodies
  • Query validation: URL query parameters
  • Params validation: Route parameters
  • Headers validation: HTTP headers
  • Files validation: Uploaded files
@ZodValidate({
  body: UserCreateSchema,
  query: PaginationSchema,
  headers: AuthHeadersSchema
})
public async createUser() {
  // All data is validated before this method runs
}

Advanced Error Handling System

The library provides multiple error formats:

// Simple format
{
  error: "Validation failed",
  message: "Email is required, Age must be at least 18"
}

// Detailed format
{
  error: "Validation failed",
  details: [
    {
      field: "body.email",
      message: "Invalid email format",
      code: "invalid_string",
      receivedValue: "invalid-email"
    }
  ]
}

// Custom format
{
  success: false,
  timestamp: "2025-07-19T10:30:00Z",
  path: "/api/users",
  errors: [...]
}

Advanced Features

File Validation System

The library includes a sophisticated file validation system:

@ZodValidate({
  files: {
    maxSize: '10MB',
    allowedTypes: ['image/jpeg', 'image/png', 'image/webp'],
    maxFiles: 5,
    required: true
  }
})
public async uploadAvatar() {}

Smart size parsing:

  • '5MB' → 5,242,880 bytes
  • '1.5GB' → 1,610,612,736 bytes
  • 1024 → 1,024 bytes

Conditional Validation

You can conditionally skip validation:

@ZodValidate(UserSchema, {
  skipValidation: (req) => {
    return req.headers['x-environment'] === 'development' ||
           req.user?.role === 'admin';
  }
})

Schema Composition & Reusability

Zod schemas can be composed and reused:

const BaseUserSchema = z.object({
    name: z.string().min(2),
    email: z.string().email(),
});

const CreateUserSchema = BaseUserSchema.extend({
    password: z.string().min(8),
});

const UpdateUserSchema = BaseUserSchema.partial().extend({
    id: z.string().uuid(),
});

OpenAPI Integration

The library automatically generates proper OpenAPI documentation from Zod schemas:

// Generates proper OpenAPI spec
@ZodValidate({ body: UserSchema })
@Post('/users')
public async createUser() {}

Simplified Decorators

For convenience, the library provides specialized decorators for common validation targets:

// These are equivalent
@ZodValidate({ body: UserSchema })
@ZodBody(UserSchema)

// Query parameters
@ZodQuery(SearchSchema)

// Route parameters
@ZodParams(IdSchema)

// Headers
@ZodHeaders(AuthSchema)

// File uploads
@ZodFiles({
  maxSize: '10MB',
  allowedTypes: ['image/jpeg', 'image/png']
})

Custom Error Handling

You can customize error responses:

@ZodValidate(UserSchema, {
  errorFormat: 'detailed', // 'simple' | 'detailed' | 'custom'
  customErrorHandler: (error, req) => {
    return {
      success: false,
      timestamp: new Date().toISOString(),
      path: req.path,
      errors: error.errors.map(e => ({
        field: e.path.join('.'),
        issue: e.message
      }))
    };
  }
})

API Reference

Decorators

  • ZodValidate: Main decorator for validating request data
  • ZodBody: Shorthand decorator for validating request body
  • ZodQuery: Shorthand decorator for validating query parameters
  • ZodParams: Shorthand decorator for validating route parameters
  • ZodHeaders: Shorthand decorator for validating request headers
  • ZodFiles: Shorthand decorator for validating file uploads

Validation Options

The ZodValidationOptions interface allows customizing validation behavior:

interface ZodValidationOptions {
    errorFormat?: 'simple' | 'detailed' | 'custom';
    customErrorHandler?: (error: any, req: Request) => any;
    skipValidation?: (req: Request) => boolean;
}

File Validation Options

The FileValidationOptions interface provides options for file validation:

interface FileValidationOptions {
    maxSize?: number | string;
    allowedTypes?: string[];
    maxFiles?: number;
    required?: boolean;
    minFiles?: number;
}

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Testing

This library includes a comprehensive test suite to ensure reliability and correctness. For detailed testing instructions, see TESTING.md.

Running Tests

# Run all tests
pnpm test

# Run tests in watch mode
pnpm test:watch

# Generate test coverage report
pnpm test:coverage

The test suite covers:

  • All decorators (ZodBody, ZodQuery, ZodParams, ZodHeaders, ZodFiles, and ZodValidate)
  • Error handling and formatting
  • Utility functions
  • Integration tests with multiple decorators

Test Coverage

We strive to maintain high test coverage for this library. You can view the coverage report by running:

pnpm test:coverage

License

MIT