samchon / typia

Super-fast/easy runtime validators and serializers via transformation
https://typia.io/
MIT License
4.65k stars 160 forks source link

Is there a similar feature as Transform in `class-transformer`? #1370

Closed leduythuccs closed 6 days ago

leduythuccs commented 1 week ago

Question

Hi there! I'm currently migrating from class-transformer to typia and nestia, and things are going pretty well so far!

However, I’ve run into a scenario where I used to rely on class-transformer in nestjs to transform fields before serializing them. This feature is particularly useful when my database schema differs from my API response.

For example, in my database, I store numbers as raw strings. Before sending the data to the frontend, I transform these strings into numbers with decimals. Here’s an example of how I used to handle this with class-transformer:

export class Foo {
  @ApiProperty({ type: number }) // User sees a number in the response
  @Transform(({ value }) => rawToNumber(value)) 
  bar: string; // Stored as a string in the database, but returned as a number to the user

  constructor(_bar: string) {
    this.bar = _bar;
  }
}

Is there a way to achieve similar functionality with typia or nestia?

Currently, I’m doing it like this, but I have many fields to transform, and this approach creates a lot of repetitive code:

interface FooTypia {
  bar: number;
}

const DBData = {
  bar: '10',
};

const response: FooTypia = {
  bar: rawToNumber(DBData.bar),
};

Thank you in advance!

samchon commented 1 week ago

Not possible in typia's paradigm.

leduythuccs commented 6 days ago

i see, thank you!

samchon commented 6 days ago

@leduythuccs

Define ${number} template type, then it would be better.