Class transformer library provides functions to transform plain javascript object in json format to an ES6 class
But I saw that it doesn't throw any error when types in json object and type defined in class has a mismatch
The class looks like follows
class MyClass {
id: string;
name: string;
age: number; // here is where i put a "abc" to test
@Type(() => Date)
date: Date;
}
On myclass2 it works fine as age(23) is a number. But in myclass1 age is set to "abc" which cannot be converted to a number type defined in the class. Yet the code goes through without any errors.
const json1 = {id: "123", name: "bob", age: "abc", date: "12/15/2019"};
const json2 = {id: "123", name: "bob", age: 23, date: "12/15/2019"};
const myclass1 = plainToClass(MyClass, json1);
const myclass2 = plainToClass(MyClass, json2);
console.log("myclass1", myclass1);
console.log("myclass2", myclass2);
In the console log you can see the although type of age is clearly defined, age's value can still be set to a string.
console log image here (i don't have enough RP points to attach a url, it s a new account)
My question is how can i get warning/error list about mismatches like this.
Thanks for the help.
It's not possible to do this using only the class transformer library.
class-transformer-validator library needs to be used in the way described in the README docs of the npm package.
In short each property of the class must be annotated with specific validator annotation. In this case, we use @IsString
and @IsNumber
class MyClass {
@IsString()
id: string;
@IsString()
name: string;
@IsNumber()
age: number;
@Type(() => Date)
date: Date;
}
And then it is validated using a method from the validator library like below.
transformAndValidate(MyClass, json1)
.then((classObject: MyClass) => {
// now you can access all your class prototype method
console.log("validated class1", classObject);
})
.catch(err => {
// here you can handle error on transformation (invalid JSON)
// or validation error (e.g. invalid email property)
console.error("validation error class1:", err);
});
The result is a list of validation errors if they exist. For the json1 like below, i expected a validation error that age is not a number in the json.
const json1 = { id: "123", name: "bob", age: "abc", date: "12/15/2019" };
The result is exactly as expected as you can see in the screenshot below. You can see the exact error encountered during deserialization and validator on `constraints' property of the error. error message screenshot (image is a link because i don't have enough RP)
A demonstration of the validation error can be seen in the same link below. https://stackblitz.com/edit/class-transformer-fxk9ay?file=src%2Fapp%2Fapp.component.ts