NestJs:使用类验证器验证对象数组

我正在尝试对数组的每个项目强制执行验证。


根据我的理解(如果我错了,请纠正我),类验证器不支持直接验证数组。它需要我们创建一个包装类。


因此,以下是课程:


export class SequenceQuery {   

    @MinLength(10, {

        message: 'collection name is too short',

      })

    collection: string;

    identifier: string;

    count: number;

}

export class SequenceQueries{

    @ValidateNested({ each: true })

    queries:SequenceQuery[];

}

以下是我的控制器:


  @Get("getSequence")

  async getSequence(@Body() query:SequenceQueries) {

    return await this.sequenceService.getNextSequenceNew(query)

  }

以下是我传递给控制器的 JSON:


{"queries":  [

    {

        "collection": "A",

        "identifier": "abc",

        "count": 1

    },

    {

        "collection": "B",

        "identifier": "mno",

        "count": 5

    },

    {

        "collection": "C",

        "identifier": "xyz",

        "count": 25

    }

]}

但它似乎不起作用。它不会抛出任何验证消息。


Cats萌萌
浏览 108回答 3
3回答

缥缈止盈

我得到了问题的解决方案。我应该将我的包装类更改为:export class SequenceQueries{    @ValidateNested({ each: true })    @Type(() => SequenceQuery) // added @Type    queries:SequenceQuery[];}但我将保留这个问题,以防万一有人有替代解决方案,例如不必创建包装类。

慕标5832272

Nestjs 中有我完整的解决方案/实现首先创建我的 DTO 类export class WebhookDto {&nbsp; @IsString()&nbsp; @IsEnum(WebHookType)&nbsp; type: string;&nbsp; @IsString()&nbsp; @IsUrl()&nbsp; url: string;&nbsp; @IsBoolean()&nbsp; active: boolean;}export class WebhookDtoArray {&nbsp; @IsArray()&nbsp; @ValidateNested({ each: true })&nbsp; @Type(() => WebhookDto)&nbsp; webhooks: WebhookDto[];}将我的 DTO 类放入我的控制器定义中&nbsp; @MessagePattern('set_webhooks')&nbsp; async setWebhooks(&nbsp; &nbsp; @Payload('body') webhookDtoArray: WebhookDtoArray,&nbsp; &nbsp; @Payload() data,&nbsp; ): Promise<Store> {&nbsp; &nbsp; return this.storeManagementService.setWebhooks(&nbsp; &nbsp; &nbsp; data.userPayload.id,&nbsp; &nbsp; &nbsp; webhookDtoArray,&nbsp; &nbsp; );&nbsp; }邮递员中我应该发送的正文的示例{&nbsp; "webhooks": [{&nbsp; &nbsp; &nbsp; "type": "InvoiceCreated",&nbsp; &nbsp; &nbsp; "url": "https://test.free.beeceptor.com",&nbsp; &nbsp; &nbsp; "active": true&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "type": "InvoiceSettled",&nbsp; &nbsp; &nbsp; "url": "https://test.free.beeceptor.com",&nbsp; &nbsp; &nbsp; "active": true&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "type": "InvoiceExpired",&nbsp; &nbsp; &nbsp; "url": "https://test.free.beeceptor.com",&nbsp; &nbsp; &nbsp; "active": true&nbsp; &nbsp; }&nbsp; ]}

www说

class-validator 确实支持数组验证,您只需添加您在 @ValidateNested( { every: true } ) 中所做的操作,您只需将 every 添加到集合元素中:export class SequenceQuery {   @MinLength(10, {    each: true,    message: 'collection name is too short',  })collection: string;identifier: string;count: number;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript