1

I am using DTO in my code, and I am getting the response as expected but in code DTOs are not throwing error for example

export class CreateCatDto {
  
  readonly name: string;
  readonly age: number;
  readonly breed: string;
  
}

In this name, age, the breed is a required field and each has their data type but while running on the postman when I am not passing all the required field or only one field into postman body I am not getting any errors like age is required if I have passed other two fields or I have given value of the parameter not according to data type like:- age : twenty five then also it should throw error but I am not getting.

So, This is class created for

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

export class Cat {

  @ApiProperty({ example: 'Kitty', description: 'The name of the Cat' })
  name: string;

  @ApiProperty({ example: 1, description: 'The age of the Cat' })
  age: number;

  @ApiProperty({
    example: 'Maine Coon',
    description: 'The breed of the Cat',
  })
  
  breed: string;
}

This is controller in which I am importing class and Dto.

import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import {
  ApiBearerAuth,
  ApiOperation,
  ApiResponse,
  ApiTags,
} from '@nestjs/swagger';

import { CatsService } from './cats.service';
import { Cat } from './classes/cat.class';
import { CreateCatDto } from './dto/create-cat.dto';

@ApiBearerAuth()
@ApiTags('cats')
@Controller('cats')
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Post()

  @ApiOperation({ summary: 'Create cat' })

  @ApiResponse({ status: 403, description: 'Forbidden.' })

  async create(@Body() createCatDto: CreateCatDto): Promise<Cat> {

    return this.catsService.create(createCatDto);
  }
}

1 Answers1

3

I don't know why you selected nestjs-swagger tag, DTO by itself will not validate inputs, maybe you need to use a ValidationPipe with the class-validator package as suggested on docs https://docs.nestjs.com/techniques/validation#validation

It's as simple as putting a decorator on your code now:

import { IsEmail, IsNotEmpty } from 'class-validator';

export class CreateCatDto {

  @IsNotEmpty()
  @IsString()
  readonly name: string;

  @IsNotEmpty()
  @IsInt()
  readonly age: number;

  @IsNotEmpty()
  readonly breed: string;

You can see all the items here: https://github.com/typestack/class-validator#validation-decorators

And if you want to sanitize the request body, you should use a serializer to help: https://docs.nestjs.com/techniques/serialization#serialization

This will show or hide your DTO properties based on decorators of each field. You need to install class-transformer package.

import { Exclude } from 'class-transformer';

export class UserEntity {
  id: number;
  firstName: string;
  lastName: string;

  @Exclude()
  password: string;

  constructor(partial: Partial<UserEntity>) {
    Object.assign(this, partial);
  }
}

It's important to remember that interceptors will run on your request and response.

arceliver
  • 336
  • 1
  • 11
  • Thank you so much !! for your response but I am trying to get that why we need any other package when we are using DTO. Please do check once more my query as I have added some more things. This code is working perfectly fine but the above issue I am still facing. – Shipra Choudhary Apr 07 '20 at 06:24
  • I'm sorry, I didn't get it. Maybe you are thinking based on your last framework or language, another way you can achieve is validating the contracts (https://github.com/balta-io/7180/tree/master/api/src/modules/backoffice) <- this is a good example. – arceliver Apr 07 '20 at 13:59