1.0.2 • Published 5 months ago
@origins-digital/zod-openapi-utils v1.0.2
@origins-digital/zod-openapi-utils
A utility package that bridges Zod schemas with OpenAPI/Swagger documentation in NestJS applications.
Installation
npm install @origins-digital/zod-openapi-utilsFeatures
- Automatic conversion of Zod schemas to OpenAPI/Swagger schemas
- Support for all Zod types and validations
- Type-safe API documentation
- Seamless integration with NestJS Swagger
- Custom format support (email, URL, UUID, CUID, etc.)
Usage
Basic Setup
import { Module } from '@nestjs/common';
import { makeOpenAPIComponents } from '@origins-digital/zod-openapi-utils';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
@Module({})
export class AppModule {
constructor() {
const config = new DocumentBuilder()
.setTitle('Your API')
.setDescription('API description')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config, {
extraModels: makeOpenAPIComponents([
// Your Zod schemas here
]),
});
SwaggerModule.setup('api', app, document);
}
}Using Zod Schemas with OpenAPI
import { z } from 'zod';
import { createZodDto } from '@origins-digital/zod-openapi-utils';
// Define your Zod schema
const UserSchema = z
.object({
id: z.string().uuid(),
email: z.string().email(),
name: z.string().min(2).max(100),
age: z.number().int().min(0).max(120),
createdAt: z.date(),
password: z.string().min(8).password(),
})
.dto('UserSchema');
// Create DTO from Zod schema
export class CreateUserDto extends createZodDto(UserSchema) {}
// Use it in your controller
@Controller('users')
export class UsersController {
@Post()
create(@Body() createUserDto: CreateUserDto) {
// The DTO will be validated against the Zod schema
return this.usersService.create(createUserDto);
}
}Supported Zod Types and Validations
- Strings: email, URL, UUID, CUID, regex patterns, min/max length
- Numbers: integers, min/max values, multipleOf
- Dates: date-time format
- Booleans
- Objects: nested schemas
- Arrays: min/max length
- Unions and Enums
- Custom Formats: password, time, etc.
- Nested types: This package is also able to detect nested types when using the .dto method, and create the reference in the openapi spec.
Error Handling
The package includes a custom exception handler for Zod validation errors that integrates with NestJS's exception handling system.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.