Open ehaynes99 opened 3 years ago
Run into the same issue with 0.5.1 - the issue appears to be after the custom transform is applied (classToPlain), a final call is made to this.transform, which is passed the string value of your date, and then proceeds to pass that to the Date constructor to transform is back into a Date object:
// If nothing change, it means no custom transformation was applied, so use the subValue.
finalValue = value[transformKey] === finalValue ? subValue : finalValue;
// Apply the default transformation
finalValue = this.transform(subSource, finalValue, type, arrayType, isSubValueMap, level + 1);
} else if ((targetType === Date || value instanceof Date) && !isMap) {
if (value instanceof Date) {
return new Date(value.valueOf());
}
if (value === null || value === undefined) return value;
return new Date(value);
}
So for 0.5.1, the solution appears to be remove the @Type decoration on the date field:
// @Type(() => Date)
// If you want to serialize as ISO8601 string, and deserialize from ISO8601 or ms or anything the Date constructor can handle
@Transform(({ value }) => value && value.toISOString(), { toPlainOnly: true })
@Transform(({ value }) => value && new Date(value), { toClassOnly: true })
exp?: Date;
@chriswhite199 curiosly, @Transform
with toPlainOnly
doesn't seem to be called on instanceToPlain
(as one would expect!) even following your suggestion :(
Struggling with @Transform
and @Type
.
import 'reflect-metadata';
import { Transform, Type, plainToInstance } from 'class-transformer';
import { IsString, ValidateNested } from 'class-validator';
class A {
@IsString()
name!: string;
}
class B {
@Transform(({ value }) => JSON.parse(value))
@Type(() => A)
@ValidateNested()
schema!: A;
}
const obj = plainToInstance(B, { schema: '{"name": "test"}' });
console.log(obj);
// Expected: B { schema: A { name: 'test' } }
// Received: B { schema: Object { name: 'test' } }
Description
When using
@Type(() => Date)
along with an@Transform
, callingplainToClass
appears to first run the custom transform, then convert that result back into a Date.Expected behavior
Actual behavior
This seems to be specific to
Date
, as doing similar with@Type(() => Number)
does not exhibit this behavior.