UNPKG

@a11d/metadata

Version:

A set of behavior-less metadata decorators.

29 lines (28 loc) 1.17 kB
/** * Creates a metadata decorator with the given key supporting both class and property metadata. * It also provides a getter for retrieving metadata by key and key-path (e.g. 'property.subProperty'). * The key-path getter needs the property to be decorated with `@type(SubPropertyType)` * for the generated decorator to be able to resolve the metadata. */ export function createMetadataDecorator(key) { function metadata(value) { return (target, propertyKey) => { Reflect.defineMetadata(key, value, target, propertyKey); }; } metadata.get = function (constructor, propertyKey) { return propertyKey === undefined ? Reflect.getMetadata(key, constructor) : Reflect.getMetadata(key, constructor.prototype, propertyKey); }; metadata.getByKeyPath = function (constructor, keyPath) { const keys = keyPath.split('.'); const key = keys.pop(); const parent = keys.reduce((previousType, key) => type.get(previousType, key), constructor); if (!parent) { return undefined; } return metadata.get(parent, key); }; return metadata; }