-
Notifications
You must be signed in to change notification settings - Fork 0
Transforms
ArteMerlow edited this page May 28, 2025
·
1 revision
Transformers allow you to overwrite the value returned from the database before validating it. They work in a similar way to validators, except that transformers actually overwrite the value.
Let's go back to the example with the same LogsDTO
class LogsDTO implements Validate {
@Result()
@IsNumber()
public id!: number;
@Result('date')
@IsDate()
public logDate!: Date;
@Result('user')
@IsSafeString()
@Min(3)
@Max(32)
public nickname!: string;
public validateErrors: Set<string> = new Set();
}Let's say you're using @kop3yka/Time library and want a regular Date to be transformed into a Time class object. You can use transformers for this
First, let's create the transformer itself.
const ToTime = () => TransformFactory.createTransform(
(value: any) => {
return new Time(value);
}
)Now we can use it for our DTO
class LogsDTO implements Validate {
@Result()
@IsNumber()
public id!: number;
@Result('date')
@ToTime()
public logDate!: Time;
@Result('user')
@IsSafeString()
@Min(3)
@Max(32)
public nickname!: string;
public validateErrors: Set<string> = new Set();
}There are also built-in transformers. For example, ToString, ToNumber, ToDate