我正在用swagger在nest js中实现小型应用程序,我有一列(postgresql(作为json对象(typeorm中的简单json类型(,嵌套对象在swagger中不可见。我的代码:
@ApiModelProperty()
@IsOptional()
readonly foo: {
boo: string[];
boo2: string;
boo3: string;
..etc
};
在swagger中,我只有空对象可见的foo,是否可以使用swagger-nest-js模块使整个json对象可见?
thx提前卡罗尔
使用显式类型
export interface Foo {
boo: string[];
boo2: string;
boo3: string;
..etc
}
和
@ApiModelPropertyOptional({ type: Foo })
@IsOptional()
readonly foo: Foo;
使用类代替
示例:
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsArray, IsNotEmpty, IsString } from 'class-validator';
import { Type } from 'class-transformer';
export class StickerRequest {
@IsNotEmpty()
@IsString()
@ApiProperty({ example: 'sticker 01' })
readonly name: string;
@ApiPropertyOptional({ example: 'This is sticker description' })
readonly description?: string;
@ApiPropertyOptional({ example: 'ami-01, ami-02' })
readonly tags?: string;
}
export class CollectionRequest {
@ApiProperty({ example: 'Ami' })
@IsNotEmpty()
@IsString()
readonly collectionName: string;
@ApiPropertyOptional({ example: 'This is collection description' })
readonly description?: string;
@ApiProperty({ example: 'fffa73e4efca9245489e2bac' })
@IsNotEmpty()
@IsString()
readonly author: string;
@ApiProperty({ type: StickerRequest }) <------- Here
@IsNotEmpty()
@IsArray()
@Type(() => StickerRequest)
stickers: StickerRequest[];
}
不要创建/使用接口的创建子Dto(如果需要,可以使用导出或不使用(例如:
export class SubDto {
@ApiModelProperty({ type: String })
@IsString()
readonly subStringOne: string;
@ApiModelProperty({ type: String })
@IsString()
readonly subStrinTwo: string;
}
export class MainDto {
@ApiModelProperty({ type: String })
@IsString()
readonly mainStringOne: string;
@ApiModelProperty({ type: [SubDto] })
@IsArray()
readonly mainArray: SubDto[];
// or do the same thing for objects
@ApiModelProperty({ type: SubDto })
@IsJSON() // @IsOject doesn't exist in Nestjs so I use @IsJSON().
readonly mainObject: SubDto;
}
我相信您使用的是旧版本的nestjs,因为@ApiModelProperty
现在被称为@ApiProperty
。我建议你将nestjs和swagger升级到他们的最新版本,并遵循以下步骤,对我来说效果很好:
https://docs.nestjs.com/recipes/swagger#openapi-招摇
希望能有所帮助。