Created
December 21, 2019 15:22
-
-
Save krizka/c83fb1966dd57997a1fc02625719387d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: