can i use validation decorators on typescript interfaces in nestJS?

Viewed 3182

according to my research we can not use validators in Interfaces , my question is if i have nested properties in a type(ex: request body property as given in the code snippet) how can i use class property validators on interfaces ?

// types.ts
// ---------------

import {  IsInt } from 'class-validator';


export interface  IRequestDto{
    readonly headers: IHeader;
    readonly body: IBody;
}

export interface IBody{
    @IsInt()
    readonly id: number;
    readonly profId: string;
}

export interface IHeader{
    readonly ContentType: string;
    readonly consumerid: string;
}



//testController.ts
// ---------------

@Controller('test')
export class TestController {
  constructor(private testService : TestService) {}

  @Post('/createProf')
  @UsePipes(new ValidationPipe())
  async createReq(@Req() request : IRequestDto) {
    const { headers, body } = request
    let localDto = new PoidBuilder()
      .setId(body.id)
      .setConsumerId(headers.consumerid)
      .setProfId(request.body.profId)
      .build()
      
      return await this.testService.createProfile(localDto)

  }

i replaced interfaces with classes but not working

import {  IsInt } from 'class-validator';


export class IRequestDto{
    readonly headers: IHeader;
    readonly body: IBody;
}

export class IBody{
    @IsInt()
    readonly id: number;
    readonly profId: string;
}

export class IHeader{
    readonly ContentType: string;
    readonly consumerid: string;
}
0 Answers
Related