Home > OS >  How to handle unexpected data from the post request body in NestJS
How to handle unexpected data from the post request body in NestJS

Time:08-22

In NestJS official tutorial of validation. We can handle wrong data type from client side post request.

// dtos/CreateUserDto.ts

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

export class CreateUserDto {
  @IsEmail()
  email: string;

  @IsNotEmpty()
  password: string;
}
// controllers/user.controller.ts

@Post()
async createUser(@Body() body: CreateUserDto) {
 return body;
}

When I create a post request like

 curl -X POST 'http://domain/user' -d '{"email": "john", "password": "changeme"}' -H "Content-Type: application/json"

I will get an expected error return.

{
    "statusCode": 400,
    "message": [
        "email must be an email"
    ],
    "error": "Bad Request"
}

my concern is an scenario that post request with unexpected data

 curl -X POST 'http://domain/user' -d '{"email": "[email protected]", "password": "changeme", "foo": "bar"}' -H "Content-Type: application/json"

I will get a return.

{
"email": "[email protected]",
"password": "changeme",
"foo": "bar"
}

I suppose the key foo would be deleted or return a system error, but it doesn't do that.

What is the best way to handle this condition ?

CodePudding user response:

Since NestJS is using class-validator you can pass all the properties to the validation pipe that are supported by class-validator options.

ValidatorOptions {
  skipMissingProperties?: boolean;
  whitelist?: boolean;
  forbidNonWhitelisted?: boolean;
  groups?: string[];
  dismissDefaultMessages?: boolean;
  validationError?: {
    target?: boolean;
    value?: boolean;
  };

  forbidUnknownValues?: boolean;
  stopAtFirstError?: boolean;
}

If you want not just strip values but throw an error when an unexpected value is passed you can use forbidUnknownValues: true.

  • Related