1
0

Custom Serializer updates

This commit is contained in:
2020-07-17 14:08:02 -04:00
parent b2769c8841
commit 6c9ccd7f82
2 changed files with 35 additions and 4 deletions

View File

@@ -31,7 +31,7 @@ export abstract class Serde<S> extends Object {
serialize() {
const pluckProperties = Reflect.getMetadata(PLUCK_PROPERTIES_KEY, this) as {[key: string]: any};
return Object.entries(this)
let serializedObj = Object.entries(this)
.filter(([key, _]) => this.removeableProperty(key))
.reduce((obj, [key, value]) => {
if (!!pluckProperties) {
@@ -50,11 +50,12 @@ export abstract class Serde<S> extends Object {
}
}
obj[key] = this.recursiveSerialize(value);
if (typeof this.customSerialize === 'function') {
obj = this.customSerialize(obj);
}
return obj;
}, {} as Partial<S>);
if (typeof this.customSerialize === 'function') {
serializedObj = this.customSerialize(serializedObj);
}
return serializedObj;
}
}

View File

@@ -0,0 +1,30 @@
import 'reflect-metadata';
import { Serde } from "src/serde";
import { Exclude } from 'src/decorators';
class NestedModel extends Serde<NestedModel> {
name: string;
@Exclude() excluded: boolean;
}
class ParentModel extends Serde<ParentModel> {
name: string;
nested: NestedModel;
@Exclude() excluded: boolean;
}
describe('Custom serlializer', () => {
it('should run custom seiralizer once', () => {
const testModel = new ParentModel().deserialize({
name: 'parent model',
excluded: true,
nested: new NestedModel().deserialize({
name: 'nested model',
excluded: true
})
});
const serializedModel = testModel.serialize();
expect(serializedModel).toEqual({ name: 'parent model', nested: { name: 'nested model' } });
});
});