NestJs serialize params with different names

40 Views Asked by At

Hy Folks,

I'm studying NestJs and I'm facing a uncommon case when use a serialization with DTO and JSON.

My Json come with follow param:

{
   "category": 1
}

But I need use this property as "type", so in my DTO is:

export class CreateClassDto {
    @IsNumber()
    type: CustomType;
}

How can I parse the "category" param from Json to param "type" on my DTO?

When I change the parameter name in DTO my Entity not parse, the service crash and I can't save indo my DB.

In Swift language I can use something like that:

struct Entity: Codable {
    let type: CustomType

    enum CodingKeys: String, CodingKey {
        case type = "category"
    }
}

Is there something like this or a decorator to say that my param received need to be my internal param?

I tried use @Expose(), but I need that "category" to be transformed in "type" for my DB and for my application.

I read this post: NestJS changing param names received in post request

But not understand so much.

Some one has an exemplo to do it?

Regard

1

There are 1 best solutions below

4
itssajan On

I dont think javascript/typescript have that capability of swift as of now. But here is my proposed workaround for your situation. I have been using this technique in all of my projects, to keeps things tidy and separate.

Dto

export class CreateClassDto {
  @IsNumber()
  category: CustomType;

  static toJSON(data: CreateClassDto) {
    return {
      type: data.category,
    };
  }
}

In Controller

async createClass(@Body() body: CreateClassDto) {
    const data = CreateClassDto.toJSON(body);
    // now you can pass the data to the respective service
    await this.classService.save(data)
}

Hope this helps.