简体   繁体   中英

How to transform field name using class transformer

I have this DTO and when I try to convert it to an object it doesn't convert to the way I want. Value converted to object but field name remains the same.

export class CreatePageGroupsDto {

@IsString()
@Expose()
name: string;


@IsString()
@Expose()
url: string;


@IsEnum(CategoryEnum)
@Expose()
category: CategoryEnum;


@Expose({ name: 'page_view' })
@Transform(({
    value = false,
}, ) => {
    const pageView: PageView = { stand_alone: value };
    return pageView;
} )

stand_alone?: boolean;
}

I have this DTO and want to convert it to an object like this

{
        'name': 'string',
        'url': 'string',
        'category': 'legal',
        'page_view': {
            stand_alone: false,
        },
    }

If you have the dto instance, and you want to covert it to an object. Your code is right.

import { Expose, instanceToPlain, Transform } from 'class-transformer';

class CreatePageGroupsDto {
  @Expose({ name: 'page_view' })
  @Transform(({ value = false }) => {
    const pageView = { stand_alone: value };
    return pageView;
  })
  stand_alone?: boolean;
}

const dto = new CreatePageGroupsDto();
dto.stand_alone = false;

console.log(instanceToPlain(dto));

Output:

{ page_view: { stand_alone: false } }

So I think you actually have a plain object from http request. And your framework like Nestjs convert the request object to the dto instance. This process is plainToInstance , not instanceToPlain . You can try swapping page_view and stand_alone like the following code:

class CreatePageGroupsDto {
  @Expose({ name: 'stand_alone' })
  @Transform(({ value = false }) => {
    const pageView = { stand_alone: value };
    return pageView;
  })
  page_view?: boolean;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM