javascriptnode.jstypescriptnestjs

How to make param required in NestJS?


I would like to make my route Query parameter required. If it is missing I expect it to throw 404 HTTP error.

@Controller('')
export class AppController {
  constructor() {}
  @Get('/businessdata/messages')
  public async getAllMessages(
    @Query('startDate', ValidateDate) startDate: string,
    @Query('endDate', ValidateDate) endDate: string,
  ): Promise<string> {
   ...
  }
}

I'm using NestJs pipes to determine if a parameter is valid, but not if it exists And I'm not sure that Pipes are made for that.

So how can I check in NestJS if my param exists if not throw an error?


Solution

  • Use class-validator. Pipes are definitely made for that !

    Example : create-user.dto.ts

    import { IsNotEmpty } from 'class-validator';
    
    export class CreateUserDto {
       @IsNotEmpty()
       password: string;
    }
    

    For more information see class-validator documentation : https://github.com/typestack/class-validator

    And NestJS Pipes & Validation documentation : https://docs.nestjs.com/pipes https://docs.nestjs.com/techniques/validation