Skip to content

Instantly share code, notes, and snippets.

@krizka
Created December 21, 2019 15:22
Show Gist options
  • Save krizka/c83fb1966dd57997a1fc02625719387d to your computer and use it in GitHub Desktop.
Save krizka/c83fb1966dd57997a1fc02625719387d to your computer and use it in GitHub Desktop.
import { jsonMember, jsonObject, TypedJSON } from 'typedjson';
import { JsonObjectMetadata } from 'typedjson/js/typedjson/metadata';
import { IJsonObjectOptions } from 'typedjson/js/typedjson/json-object';
import { ParameterlessConstructor } from 'typedjson/js/typedjson/types';
import { Serializer } from 'typedjson/js/typedjson/serializer';
const META_FIELD = '__typedJsonJsonObjectMetadataInformation__';
function findRootMetaInfo(proto): JsonObjectMetadata {
const protoProto = Object.getPrototypeOf(proto);
if (!protoProto || !protoProto[META_FIELD]) {
return proto[META_FIELD];
}
return findRootMetaInfo(protoProto);
}
export function object(name: string, options?: IJsonObjectOptions<any>): ClassDecorator {
return (target: Function) => {
jsonObject({ name, ...options })(target as ParameterlessConstructor<any>);
// find root type meta info in TypedJSON, knownTypes needed to understand our type is from our hierarchy
findRootMetaInfo(target.prototype).knownTypes.add(target);
};
}
// ..........
@object('root')
class RootType {
@jsonMember
public _id: string = "";
}
@object('childType')
class ChildType extends RootType {
}
const serializer = new TypedJSON(RootType);
@krizka
Copy link
Author

krizka commented Dec 21, 2019

Hope, it will be helpful for someone who will search, I made some util function and new decorator to achieve polymorphic behaviour, which worked quite well for me. it is added knownTypes to root type automatically, searching for root element:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment