Nest js - Change capital letter for dashed in ToJSON method

961 views Asked by At

I have the method:

@Entity()
export class Picklist extends BaseD2CEntity {
  @ApiHideProperty()
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ name: 'picklist_name' })
  @IsString()
  @ApiProperty({ type: String, description: 'picklist_name' })
  picklistName: string;

  toJSON() {
    return classToPlain(this);
  }

}

At the moment to serialize the object, with:

myPicklist.picklist.toJSON(); I get:

{ id: 7, picklistName: "status", }

What is correct. But, I need to replace the capital letter of picklistName and replace it for _ like, picklist_name, as in the decorator @Column. Is this possible?

1

There are 1 answers

0
Kim Kern On BEST ANSWER

Expose properties with different name

You can expose properties with a different name in the serialization with class-transformer's @Expose decorator, see this answer:

@Expose({ name: 'picklist_name' })
picklistName: string;

Built-in ClassSerializerInterceptor

Instead of defining the toJSON method yourself, you can use the built-in ClassSerializerInterceptor to automatically serialize your entities when returning them from a controller method, see this answer.

@UseInterceptors(ClassSerializerInterceptor)