tsoa-zod-validator
v0.1.0
Published
Zod validation decorators for tsoa
Maintainers
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-validatorCore 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 dataZodBody: Shorthand decorator for validating request bodyZodQuery: Shorthand decorator for validating query parametersZodParams: Shorthand decorator for validating route parametersZodHeaders: Shorthand decorator for validating request headersZodFiles: 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:coverageThe test suite covers:
- All decorators (
ZodBody,ZodQuery,ZodParams,ZodHeaders,ZodFiles, andZodValidate) - 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:coverageLicense
MIT
