UNPKG

typed-reflector

Version:

Metadata reflector with typing support.

133 lines (129 loc) 3.44 kB
// src/reflector.ts import "reflect-metadata"; // src/utility/utility.ts function isClass(target) { if (typeof target !== "function") { return false; } const proto = target.constructor; return proto === Function; } function getClass(target) { return isClass(target) ? target : getClass(target.constructor); } // src/reflector.ts var Reflector = class { get(metadataKey, instance, key) { const instanceClass = getClass(instance); if (key) { return Reflect.getMetadata(metadataKey, instanceClass, key); } else { return Reflect.getMetadata(metadataKey, instanceClass); } } getArray(metadataKey, instance, key) { return this.get(metadataKey, instance, key) || []; } getProperty(metadataKey, instance, key, alternate) { const valueFromClass = this.getArray(metadataKey, instance); const valueFromAlternate = alternate ? this.getArray(metadataKey, alternate) : []; const valueFromProperty = this.getArray(metadataKey, instance, key); return [ ...valueFromClass, ...valueFromAlternate, ...valueFromProperty ]; } }; // src/setter.ts import "reflect-metadata"; var MetadataSetter = class { getMetadataInDecorator(metaKey, target, key) { if (key) { return Reflect.getMetadata(metaKey, target, key); } else { return Reflect.getMetadata(metaKey, target); } } setMetadataInDecorator(metaKey, value, target, key) { if (key) { return Reflect.defineMetadata(metaKey, value, target, key); } else { return Reflect.defineMetadata(metaKey, value, target); } } transform(metadataKey, metadataValueFun, keysIndexMeta) { return (target, key) => { const targetClass = getClass(target); const oldValue = this.getMetadataInDecorator( metadataKey, targetClass, key ); const newValue = metadataValueFun(oldValue); this.setMetadataInDecorator(metadataKey, newValue, targetClass, key); if (keysIndexMeta) { const keysDec = this.appendUnique(keysIndexMeta, key); keysDec(targetClass); } }; } set(metadataKey, metadataValue, keysIndexMeta) { return this.transform( metadataKey, () => metadataValue, keysIndexMeta ); } append(metadataKey, metadataValue, keysIndexMeta) { return this.transform( metadataKey, (arr) => { const newArr = arr || []; newArr.push(metadataValue); return newArr; }, keysIndexMeta ); } appendUnique(metadataKey, metadataValue, keysIndexMeta) { return this.transform( metadataKey, (arr) => { const newArr = arr || []; if (newArr.includes(metadataValue)) { return newArr; } newArr.push(metadataValue); return newArr; }, keysIndexMeta ); } concat(metadataKey, metadataValue, keysIndexMeta) { return this.transform( metadataKey, (arr) => (arr || []).concat(metadataValue), keysIndexMeta ); } param(metadataKey, metadataValue, keysIndexMeta) { return (obj, key, i) => { const dec = this.transform( metadataKey, (arr) => { const newArr = arr || []; newArr[i] = metadataValue; return newArr; }, keysIndexMeta ); dec(obj, key); }; } }; export { MetadataSetter, Reflector }; //# sourceMappingURL=index.mjs.map