Metadata library that created to resolve your pain with all mappers and type-checking of objects after serialization or deserialization.
Don`t use the spread operator for copying of your models because prototypes chain will be lost after it!
- Add a dependency to your package.json file:
npm install serialize-ts --save or yarn add serialize-ts;
2. Change a tsconfig.json:
{
...compilerOptions: {...emitDecoratorMetadata: true,...
},
...}Simple model:
classTestModel{
@Field()
@Name("sever-id")id: number;
@Field()fullName: string;ignoredField: any;}constmodel=newTestModel();model.id=12;model.fullName="Default full name";model.ignoredField={customName: "test"};console.log(serialize(model));/*Output -> { server-id: 12, fullName: 'Default full name'}*/constobj={"server-id": 12,fullName: "Default full name","custom-date-name": "2017-08-01T06:09:53.802Z"};console.log(deserialize(obj,TestModel));/*Output -> TestModel { id: 12, fullName: 'Default full name', startDate: new Date('2017-08-01T06:09:53.802Z')}*/Nested models:
classOuterModel{
@Field()id: number;
@Field()nestedModel: NestedModel;}
@Model()classNestedModel{
@Field()firstField: number;
@Field()secondField: string;}constobj={id: 12,nestedModel: {firstField: 24,secondField: 'Some awesome string!'}};constouterModel=deserialize(obj,TestModel);console.log(outerModel);/* Output -> OuterModel { id: 12, nestedModel: NestedModel { firstField: 24, secondField: "Some awesome string!" } }*/console.log(serialize(outerModel));/* Output -> { id: 12, nestedModel: { firstField: 24, secondField: "Some awesome string!" } }*/Arrays:
classTest{
@Field()id: number;
@Field()
@Name('numbers')
@Serializer(newArraySerializer(newPrimitiveSerializer()))arrayOfNumbers: number[];}constobj={id: 12,numbers: [12,24,36,48]};constdeserializedModel=deserialize(obj,Test);console.log(deserializedModel);/* Output -> Test { id: 12, arrayOfNumber: [12, 24, 36, 48] }*/Custom serializers:
classCustomSerializerimplementsSerializer<Object>{serialize(model: Object){// Do some custom logic}deserialize(json: Object){// Do your custom logic and return deserialized object}}classModel{
@Field()id: 12;
@Field()
@Serializer(newCustomSerializer())customField: any;}If you have some troubles with serialization without serializer decorator definition, you are able to define it with @Serializer(YourCustomModel) or with some default type like Date or String.
I am waiting for the issues of course!