如何让Nest.js中的Swagger映射未被使用的实体?
解决Nest.js中未被业务代码引用的Swagger实体文档化问题
当你用Prisma作为ORM,定义了UserEntity但没在业务代码(比如@Body、@Param装饰器)中直接使用时,Swagger不会自动扫描到这个实体。可以用以下几种方式解决:
方法一:手动在Swagger文档配置中添加实体
在项目的main.ts里,创建Swagger文档时,通过addSchema方法手动将UserEntity加入到文档定义中。这样不管实体是否被业务代码引用,Swagger都会把它展示出来。
示例代码:
import { NestFactory } from '@nestjs/core'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; import { AppModule } from './app.module'; import { UserEntity } from './entities/user.entity'; async function bootstrap() { const app = await NestFactory.create(AppModule); const config = new DocumentBuilder() .setTitle('API 文档') .setDescription('项目API详细描述') .setVersion('1.0') .addTag('users') .addSchema(UserEntity) // 手动注册实体到Swagger .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api', app, document); await app.listen(3000); } bootstrap();
方法二:用@ApiExtraModels装饰器注册实体
在任意一个控制器上添加@ApiExtraModels(UserEntity)装饰器,Swagger会自动扫描并将该实体加入到文档的components/schemas中。如果需要在接口响应或请求体中明确关联这个实体,还可以配合getSchemaRef来引用。
示例代码:
import { Controller } from '@nestjs/common'; import { ApiExtraModels, ApiTags, ApiResponse, getSchemaRef } from '@nestjs/swagger'; import { UserEntity } from '../entities/user.entity'; @ApiTags('users') @ApiExtraModels(UserEntity) // 注册实体到Swagger @Controller('users') export class UserController { @ApiResponse({ status: 200, description: '获取单个用户信息', schema: getSchemaRef(UserEntity) // 明确引用实体作为响应结构 }) async getUser() { // 这里直接用Prisma查询数据即可,无需依赖UserEntity实例 return prisma.user.findUnique({ where: { id: 'xxx' } }); } }
方法三:创建空DTO继承实体并在业务代码中引用
如果不想手动注册,可以创建一个空的DTO类继承UserEntity,然后在控制器的@Body、@ApiBody或@ApiResponse中使用这个DTO。Swagger会自动识别DTO的结构,间接把UserEntity的字段展示在文档里。
示例代码:
// src/users/dto/user.dto.ts import { UserEntity } from '../entities/user.entity'; export class UserDto extends UserEntity {} // src/users/user.controller.ts import { Controller, Post, Body } from '@nestjs/common'; import { ApiBody, ApiTags } from '@nestjs/swagger'; import { UserDto } from './dto/user.dto'; import { PrismaService } from '../prisma/prisma.service'; @ApiTags('users') @Controller('users') export class UserController { constructor(private readonly prisma: PrismaService) {} @Post() @ApiBody({ type: UserDto }) // 使用DTO作为请求体结构 async createUser(@Body() userData: UserDto) { // 直接用Prisma写入数据,userData的类型会自动继承UserEntity的定义 return this.prisma.user.create({ data: userData }); } }
内容的提问来源于stack exchange,提问作者dokichan
相关产品推荐
相关产品推荐

