首页 > 解决方案 > 为什么这个Schema为空.....如何在nestjs中设置@ApiProperty

问题描述

我像这样在 Dto 中创建 @ApiProperty()

export class UpdateMeassageDto {

@ApiProperty()

message: {

    hash: string;


    created_at: Date;


    updated_at: Date;
}

}

然后它得到一个像这样的空结果

https://i.stack.imgur.com/kYGP5.jpg

标签: typescriptswaggernestjsnestjs-swagger

解决方案


您可以通过以下方式进行

import { ApiProperty, getSchemaPath } from '@nestjs/swagger';

export class MessageDto {
    @ApiProperty({
        type: 'string',
        example: 'hx1231',
    })
    hash: string;

    @ApiProperty({
        type: 'date',
        example: '2021-08-04T19:39:00.829Z',
    })
    created_at: Date;

    @ApiProperty({
        type: 'string',
        format: 'date-time',
        example: '2021-08-04T19:39:00.829Z',
    })
    updated_at: Date;
}

export class UpdateMessageDto {
    @ApiProperty({
        type: 'array',
        items: { $ref: getSchemaPath(MessageDto) },
    })
    message: MessageDto;
}

每个属性都需要 ApiProperty。您可以使用 $ref 在另一个 DTO 中使用一个 DTO。在 DTO 中也使用类验证器会很好。


推荐阅读