Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 836
infodev Avatar asked Oct 23 '18 13:10

infodev


People also ask

How do I get parameters in Nestjs?

To get all query parameter values from a GET request, you can use the @Query() decorator function from the @nestjs/common module inside the parameter brackets of the controller's respective method in Nestjs.

How do I change my Nestjs status code?

Status code We can easily change this behavior by adding the @HttpCode(...) decorator at a handler level. Hint Import HttpCode from the @nestjs/common package. Often, your status code isn't static but depends on various factors.

What is ValidationPipe?

The ValidationPipe provides a convenient approach to enforce validation rules for all incoming client payloads, where the specific rules are declared with simple annotations in local class/DTO declarations in each module.

What is @body in Nestjs?

To instruct Nestjs that we need the body values from the request, we should use the @Body() decorator function from the @nestjs/common module before the body parameter. Doing this will bind the body values from the request to the body parameter in the createPost() method.


3 Answers

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

like image 194
Phie Avatar answered Oct 22 '22 17:10

Phie


NestJS does not provide a decorator (like @Query) that detects undefined value in request.query[key].

You can write custom decorator for that:

import { createParamDecorator, ExecutionContext, BadRequestException } from '@nestjs/common'

export const QueryRequired = createParamDecorator(
  (key: string, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest()

    const value = request.query[key]

    if (value === undefined) {
      throw new BadRequestException(`Missing required query param: '${key}'`)
    }

    return value
  }
)

Then use @QueryRequired decorator as you would use @Query:

@Get()
async someMethod(@QueryRequired('requiredParam') requiredParam: string): Promise<any> {
    ...
}
like image 40
Hnennyi Andrii Avatar answered Oct 22 '22 18:10

Hnennyi Andrii


There hava a easy way to valide you parameter, https://docs.nestjs.com/techniques/validation

like image 5
jkchao Avatar answered Oct 22 '22 16:10

jkchao