|
1 | 1 | import "reflect-metadata";
|
| 2 | +import {expect} from "chai"; |
2 | 3 | import {classToPlain, plainToClass} from "../../src/index";
|
3 | 4 | import {defaultMetadataStorage} from "../../src/storage";
|
4 | 5 | import {Expose, Transform, Type} from "../../src/decorators";
|
@@ -157,5 +158,63 @@ describe("custom transformation decorator", () => {
|
157 | 158 | objArg.should.be.equal(user);
|
158 | 159 | typeArg.should.be.equal(TransformationType.CLASS_TO_PLAIN);
|
159 | 160 | });
|
| 161 | + |
| 162 | + let model: any; |
| 163 | + it ("should serialize json into model instance of class Person", () => { |
| 164 | + expect(() => { |
| 165 | + const json = { |
| 166 | + name: "John Doe", |
| 167 | + address: { |
| 168 | + street: "Main Street 25", |
| 169 | + tel: "5454-534-645", |
| 170 | + zip: 10353, |
| 171 | + country: "West Samoa" |
| 172 | + }, |
| 173 | + age: 25, |
| 174 | + hobbies: [ |
| 175 | + { type: "sport", name: "sailing" }, |
| 176 | + { type: "relax", name: "reading" }, |
| 177 | + { type: "sport", name: "jogging" }, |
| 178 | + { type: "relax", name: "movies" } |
| 179 | + ] |
| 180 | + }; |
| 181 | + class Hobby { |
| 182 | + public type: string; |
| 183 | + public name: string; |
| 184 | + } |
| 185 | + class Address { |
| 186 | + public street: string; |
| 187 | + |
| 188 | + @Expose({ name: "tel" }) |
| 189 | + public telephone: string; |
| 190 | + |
| 191 | + public zip: number; |
| 192 | + |
| 193 | + public country: string; |
| 194 | + } |
| 195 | + class Person { |
| 196 | + public name: string; |
| 197 | + |
| 198 | + @Type(() => Address) |
| 199 | + public address: Address; |
| 200 | + |
| 201 | + @Type(() => Hobby) |
| 202 | + @Transform(value => value.filter((hobby: any) => hobby.type === "sport"), { toClassOnly: true }) |
| 203 | + public hobbies: Hobby[]; |
| 204 | + |
| 205 | + public age: number; |
| 206 | + } |
| 207 | + model = plainToClass(Person, json); |
| 208 | + expect(model instanceof Person); |
| 209 | + expect(model.address instanceof Address); |
| 210 | + model.hobbies.forEach((hobby: Hobby) => expect(hobby instanceof Hobby && hobby.type === "sport")); |
| 211 | + }).to.not.throw(); |
| 212 | + }); |
| 213 | + |
| 214 | + it ("should serialize a model into json", () => { |
| 215 | + expect(() => { |
| 216 | + classToPlain(model); |
| 217 | + }).to.not.throw(); |
| 218 | + }); |
160 | 219 |
|
161 | 220 | });
|
0 commit comments