Custom Serializer updates
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
30
tests/decorators/custom-serializer.spec.ts
Normal file
30
tests/decorators/custom-serializer.spec.ts
Normal 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' } });
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user