typia icon indicating copy to clipboard operation
typia copied to clipboard

New Function to Perform Class Transformation

Open benoit-scnd opened this issue 2 years ago • 4 comments

Feature Request

A new function named classTransform that converts a given input into an instance of a specific class.

The function could have the following signature:

typia.classTransform<T>(input: Primitive<T>): T;

This function takes two arguments:

  • input: The primitive input to be converted.
  • T: The target class that the input should be transformed into.

The function should return an instance of the class T with the given input.

This function would be particularly useful for converting raw input data into class instances. This issue is critical as it prevents proper type validation and transformation of the incoming request body, a common requirement in type-safe server-side applications. (see https://github.com/samchon/nestia/issues/431)

Example Usage

Here is an example of how this function could be used:

class Foo {
  constructor(public value: string) {}

  bar() {
    return this.value;
  }
}

const input = {value: "test"};
const transformed = typia.classTransform<Test>(input);
console.log(transformed.bar()); // Should log: "test"

benoit-scnd avatar Jun 26 '23 10:06 benoit-scnd

@samchon ,

Here is the way to do a nested conversion with the package class-transformer:

import { Type, plainToClass } from 'class-transformer';

class Bar {
  value: string;
}

class Foo {
  @Type(() => Bar)
  bar: Bar;
}

const foo = plainToClass(Foo, { bar: { value: 'test' } });

So the challenge is to find a way to guess the type without decorator and rewrite the plainToClass function to obtain better performances.

benoit-scnd avatar Jun 26 '23 13:06 benoit-scnd

Will try it but cannot sure 100% success

samchon avatar Jun 29 '23 15:06 samchon

This would be very much appreciated - would it be possible for you to suggest the different components needed for this and to tell us where you'd like them to be integrated? That'd make it a lot easier to create a reasonable PR without having to read/understand the entire codebase first.

Maybe a short introduction to the workings of the different components (folders) would also do. Thanks!

marcesengel avatar Jul 29 '23 06:07 marcesengel

@marcesengel Implementation code of clone() may be helpful, and seems like almost same with this feature.

Looking at below codes, then you may understand how typia's function has been developed.

If you want to implement this feature by yourself, add classify<T>() function declarations in module.ts file, and implement your logic on a new file ClasstifyProgrammer.ts. After that, link module.ts file's function declaration to the ClassifyProgrammer by adding ClassifyTransformer from CallExpressionTransformer.ts.

Additional functions like assertClassify(), you can make it easily just by combining like AssertCloneProgrammer.

samchon avatar Jul 30 '23 10:07 samchon