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?
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.
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.
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.
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.
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
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> {
...
}
There hava a easy way to valide you parameter, https://docs.nestjs.com/techniques/validation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With