nestjs-typeorm-paginate icon indicating copy to clipboard operation
nestjs-typeorm-paginate copied to clipboard

class-transformer usage

Open kevin-lot opened this issue 3 years ago • 1 comments

How can I use https://github.com/typestack/class-transformer to have group serialization?

In my controller, I want to excludeAll and perform serialization only on the properties I want to serialize. If I do this, no properties are serialized at all, which seems normal since "items" and "meta" do not have the @Expose annotation.

How can I do this?

Best regards.

kevin-lot avatar May 20 '22 10:05 kevin-lot

I believe this solution is what you need. Hope it will help. By this way you won't need to serialize at controller anymore

Create the instance class you need to transform

import { plainToInstance, Expose, Exclude } from 'class-transformer';

export class UserTransformed
{
  @Expose({ name: 'user_name' })
  userName: string;

  @Exclude()
  @Expose({ name: 'password' })
  password: string;

  @Expose({ name: 'created_at' })
  createdAt: Date;

  @Expose({ name: 'updated_at' })
  updatedAt: Date;
}


async transformed() { 
    const result = await this.paginate(queryBuilder, {
      limit,
      page,
    });

    return {
      user: plainToInstance(UserTransformed, result.items),
      paging: result.meta,
    };
}

TonyDo99 avatar Mar 09 '25 03:03 TonyDo99