如何在NestJS中通过Swagger生成简易Schema?
在NestJS中生成可复用的string类型Swagger Schema
问题场景
按照NestJS官方文档的方式定义DTO后,生成的Swagger Schema会将NodeId解析为object类型,但我需要将其生成为string类型的可复用简易Schema,无需手动编辑Swagger YAML文件。
当前实现与生成结果
当前DTO代码
import { ApiProperty } from '@nestjs/swagger'; export class NodeId { @ApiProperty({ minimum: 40, maximum: 40, readOnly: true, }) id: string; } export class Position { @ApiProperty({ readOnly: true, example: 0 }) x: number; @ApiProperty({ readOnly: true, example: 0 }) y: number; } export class Node { @ApiProperty() nodeId: NodeId; @ApiProperty() position: Position; }
生成的NodeId Schema(YAML)
NodeId: type: object properties: id: type: string minimum: 40 maximum: 40 readOnly: true required: - id
期望的Schema结果
希望生成的NodeId是string类型的可复用Schema,如下:
NodeId: type: string minimum: 40 maximum: 40 readOnly: true
可行解决方案
你可以通过两种方式实现这个需求:
方案1:自定义Schema配置+TypeScript类型(推荐)
定义可复用的Schema配置和对应TypeScript类型,在需要的地方直接引用:
import { ApiProperty } from '@nestjs/swagger'; // 定义可复用的NodeId类型 export type NodeId = string; // 定义对应的Swagger Schema配置 export const NodeIdSchema = { type: 'string', minimum: 40, maximum: 40, readOnly: true, }; export class Position { @ApiProperty({ readOnly: true, example: 0 }) x: number; @ApiProperty({ readOnly: true, example: 0 }) y: number; } export class Node { @ApiProperty({ schema: NodeIdSchema }) nodeId: NodeId; @ApiProperty() position: Position; }
方案2:使用@Schema装饰器修改类元数据
如果坚持用类的方式定义,可通过@Schema装饰器覆盖类的Swagger元数据,将其标记为string类型:
import { ApiProperty, Schema } from '@nestjs/swagger'; @Schema({ type: 'string', minimum: 40, maximum: 40, readOnly: true, }) export class NodeId {} export class Position { @ApiProperty({ readOnly: true, example: 0 }) x: number; @ApiProperty({ readOnly: true, example: 0 }) y: number; } export class Node { @ApiProperty({ type: () => NodeId }) nodeId: NodeId; @ApiProperty() position: Position; }
两种方式都能让Swagger模块直接生成你需要的string类型Schema,无需手动修改YAML文件。
内容的提问来源于stack exchange,提问作者Meta
相关产品推荐
相关产品推荐

