亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

NestJs:使用類驗證器驗證對象數組

NestJs:使用類驗證器驗證對象數組

Cats萌萌 2023-09-07 10:12:18
我正在嘗試對數組的每個項目強制執行驗證。根據我的理解(如果我錯了,請糾正我),類驗證器不支持直接驗證數組。它需要我們創建一個包裝類。因此,以下是課程: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    }]}但它似乎不起作用。它不會拋出任何驗證消息。
查看完整描述

3 回答

?
縹緲止盈

TA貢獻2041條經驗 獲得超4個贊

我得到了問題的解決方案。


我應該將我的包裝類更改為:


export class SequenceQueries{

    @ValidateNested({ each: true })

    @Type(() => SequenceQuery) // added @Type

    queries:SequenceQuery[];

}

但我將保留這個問題,以防萬一有人有替代解決方案,例如不必創建包裝類。


查看完整回答
反對 回復 2023-09-07
?
慕標5832272

TA貢獻1966條經驗 獲得超4個贊

Nestjs 中有我完整的解決方案/實現


首先創建我的 DTO 類

export class WebhookDto {

  @IsString()

  @IsEnum(WebHookType)

  type: string;


  @IsString()

  @IsUrl()

  url: string;


  @IsBoolean()

  active: boolean;

}


export class WebhookDtoArray {

  @IsArray()

  @ValidateNested({ each: true })

  @Type(() => WebhookDto)

  webhooks: WebhookDto[];

}

將我的 DTO 類放入我的控制器定義中

  @MessagePattern('set_webhooks')

  async setWebhooks(

    @Payload('body') webhookDtoArray: WebhookDtoArray,

    @Payload() data,

  ): Promise<Store> {

    return this.storeManagementService.setWebhooks(

      data.userPayload.id,

      webhookDtoArray,

    );

  }

郵遞員中我應該發送的正文的示例

{

  "webhooks": [{

      "type": "InvoiceCreated",

      "url": "https://test.free.beeceptor.com",

      "active": true

    },

    {

      "type": "InvoiceSettled",

      "url": "https://test.free.beeceptor.com",

      "active": true

    },

    {

      "type": "InvoiceExpired",

      "url": "https://test.free.beeceptor.com",

      "active": true

    }

  ]

}


查看完整回答
反對 回復 2023-09-07
?
www說

TA貢獻1775條經驗 獲得超8個贊

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;

}

查看完整回答
反對 回復 2023-09-07
  • 3 回答
  • 0 關注
  • 145 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號