Home > OS >  What do you call the "@Body()" in the following function signature: "create(@Body() c
What do you call the "@Body()" in the following function signature: "create(@Body() c

Time:05-11

I'm trying to learn NestJS, and I noticed the following function signatures on their documentation:

@Post()
async create(@Body() createCatDto: CreateCatDto) {
  this.catsService.create(createCatDto);
}

it's my first time seeing the @Body() before the parameter name. What is it? and what do you call it? It looks like its a decorator but feels like it somehow casts the parameter, but i think that's the point of the parameter type right?

Regards,

CodePudding user response:

These are called param decorators you can further read this for a better explanation https://docs.nestjs.com/custom-decorators#param-decorators

Coming to your question @Body() is a param decorator which parses your incoming JSON payload into the Dto (Data Transfer Object) Structure Provided (Dto can be a class or can be an interface).

For example assume the following Dto Structure :

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

This structure expects the client-side to pass the following structure JSON

{
 "name" : "abc",
 "age"  : 22,
 "breed" : "abc"

}

And then @Body() param decorator will parse the incoming JSON payload to the Dto provided.

And hence you can simply get the JSON values in the shape of class object or inteface Like this :

@Post()
async create(@Body() createCatDto: CreateCatDto) {
  console.log(createCatDto.name);
  console.log(createCatDto.age);
  console.log(createCatDto.breed);
  this.catsService.create(createCatDto);
}

Note: Any parameter missing will result undefined in Dto.

  • Related