tsoa-zod-validator
Version:
Zod validation decorators for tsoa
288 lines (214 loc) • 6.27 kB
Markdown
# 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
```bash
# 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:
```typescript
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
```typescript
@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:
```typescript
// 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:
```typescript
@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:
```typescript
@ZodValidate(UserSchema, {
skipValidation: (req) => {
return req.headers['x-environment'] === 'development' ||
req.user?.role === 'admin';
}
})
```
### Schema Composition & Reusability
Zod schemas can be composed and reused:
```typescript
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:
```typescript
// 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:
```typescript
// 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:
```typescript
@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:
```typescript
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:
```typescript
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](TESTING.md).
### Running Tests
```bash
# 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:
```bash
pnpm test:coverage
```
## License
MIT