@anatine/zod-nestjs

中文文档
2.0.12发布于 2025/04/06MITTypeScriptCommonJS近 30 天下载 52.6万

Zod helper methods for NestJS

原始使用文档
文档目录8 节
  1. Installation
  2. Usage
  3. Generate a schema
  4. Use the schema in your controller
  5. Set up your app
  6. Future goals
  7. Credits
  8. zod-dto

@anatine/zod-nestjs

Helper methods for using Zod in a NestJS project.

  • Validation pipe on data
  • Patch to Swagger module

Installation

@anatine/zod-openapi, openapi3-ts, and zod are peer dependencies instead of dependant packages. While zod is necessary for operation, openapi3-ts is for type-casting. @anatine/zod-openapi does the actual conversion

npm install openapi3-ts zod @anatine/zod-openapi @anatine/zod-nestjs 

Usage

Generate a schema

Use Zod to generate a schema. Additionally, use @anatidae/zod-openapi to extend a schema for OpenAPI and Swagger UI.

Example schema:

import { createZodDto } from '@anatine/zod-nestjs';
import { extendApi } from '@anatine/zod-openapi';
import { z } from 'zod';
export const CatZ = extendApi(
  z.object({
    name: z.string(),
    age: z.number(),
    breed: z.string(),
  }),
  {
    title: 'Cat',
    description: 'A cat',
  }
);
export class CatDto extends createZodDto(CatZ) {}
export class UpdateCatDto extends createZodDto(CatZ.omit({ name: true })) {}
export const GetCatsZ = extendApi(
  z.object({
    cats: extendApi(z.array(z.string()), { description: 'List of cats' }),
  }),
  { title: 'Get Cat Response' }
);
export class GetCatsDto extends createZodDto(GetCatsZ) {}
export const CreateCatResponseZ = z.object({
  success: z.boolean(),
  message: z.string(),
  name: z.string(),
});
export class CreateCatResponseDto extends createZodDto(CreateCatResponseZ) {}
export class UpdateCatResponseDto extends createZodDto(
  CreateCatResponseZ.omit({ name: true })
) {}

Use the schema in your controller

This follows the standard NestJS method of creating controllers.

@nestjs/swagger decorators should work normally.

Example Controller

import { ZodValidationPipe } from '@anatine/zod-nestjs';
import {
  Body,
  Controller,
  Get,
  Param,
  Patch,
  Post,
  UsePipes,
} from '@nestjs/common';
import { ApiCreatedResponse } from '@nestjs/swagger';
import {
  CatDto,
  CreateCatResponseDto,
  GetCatsDto,
  UpdateCatDto,
  UpdateCatResponseDto,
} from './cats.dto';
@Controller('cats')
@UsePipes(ZodValidationPipe)
export class CatsController {
  @Get()
  @ApiCreatedResponse({
    type: GetCatsDto,
  })
  async findAll(): Promise<GetCatsDto> {
    return { cats: ['Lizzie', 'Spike'] };
  }
  @Get(':id')
  @ApiCreatedResponse({
    type: CatDto,
  })
  async findOne(@Param() { id }: { id: string }): Promise<CatDto> {
    return {
      name: `Cat-${id}`,
      age: 8,
      breed: 'Unknown',
    };
  }
  @Post()
  @ApiCreatedResponse({
    description: 'The record has been successfully created.',
    type: CreateCatResponseDto,
  })
  async create(@Body() createCatDto: CatDto): Promise<CreateCatResponseDto> {
    return {
      success: true,
      message: 'Cat created',
      name: createCatDto.name,
    };
  }
  @Patch()
  async update(
    @Body() updateCatDto: UpdateCatDto
  ): Promise<UpdateCatResponseDto> {
    return {
      success: true,
      message: `Cat's age of ${updateCatDto.age} updated`,
    };
  }
}

NOTE: Responses have to use the ApiCreatedResponse decorator when using the @nestjs/swagger module.

Set up your app

Patch the swagger so that it can use Zod types before you create the document.

Example Main App

import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { CatsModule } from './app/cats.module';
import { patchNestjsSwagger } from '@anatine/zod-nestjs';
async function bootstrap() {
  const app = await NestFactory.create(CatsModule);
  const globalPrefix = 'api';
  app.setGlobalPrefix(globalPrefix);
  const config = new DocumentBuilder()
    .setTitle('Cats example')
    .setDescription('The cats API description')
    .setVersion('1.0')
    .addTag('cats')
    .build();
  patchNestjsSwagger(); // <--- This is the hacky patch using prototypes (for now)
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);
  const port = process.env.PORT || 3333;
  await app.listen(port, () => {
    Logger.log('Listening at http://localhost:' + port + '/' + globalPrefix);
  });
}
bootstrap();

Future goals

  • Remove dependency on @nestjs/swagger by providing a Swagger UI.
  • Expand to create an express-only wrapper (without NestJS)
  • Auto generate client side libs with Zod validation.

Credits

  • zod-dto

    Extensive use and inspiration from zod-dto.

版本与发布记录

@anatine/zod-nestjs 共发布 37 个版本,首次发布于 2021/07/12;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.0.12latest2025/04/061.6 年前
2.0.112025/04/041.6 年前
2.0.102025/01/201.8 年前
2.0.92024/06/212 年前
2.0.82024/03/302 年前
2.0.72024/03/202 年前

关于 @anatine/zod-nestjs 的常见问题

@anatine/zod-nestjs 是什么?

Zod helper methods for NestJS

如何安装 @anatine/zod-nestjs?

在项目目录运行 npm install @anatine/zod-nestjs,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@anatine/zod-openapi(^2.0.1)、@nestjs/common(^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0)、@nestjs/swagger(^6.0.0 || ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0)、openapi3-ts(^4.1.2)、zod(^3.20.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@anatine/zod-nestjs 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@anatine/zod-nestjs 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@anatine/zod-nestjs 可以商用吗?

@anatine/zod-nestjs 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@anatine/zod-nestjs 的下载量有多少?

根据 npm 官方下载统计,@anatine/zod-nestjs 在 2026/10/06 – 2026/11/04 这 30 天内被下载 526,258 次,日均约 17,542 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@anatine/zod-nestjs 还在维护吗?

最新版本 2.0.12 发布于 2025/04/06(1.6 年前);至今共发布 37 个版本,其中过去 12 个月发布了 0 个;首次发布于 2021/07/12。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。