UNPKG

2.19 kBPlain TextView Raw
1//import 'reflect-metadata'
2import {ReturnTypeKey, TypeKey} from "./Constants"
3const log = require('./log').create(__filename)
4
5
6/**
7 * Simple pass thru to define metadata
8 *
9 * @param metadataKey
10 * @param metadata
11 * @param target
12 * @param targetKey
13 */
14export function setMetadata(metadataKey:string,metadata:any,target:any,targetKey?:string) {
15 Reflect.defineMetadata(metadataKey,metadata,target,targetKey)
16}
17
18/**
19 * Get metadata
20 *
21 * @param metadataKey
22 * @param target
23 * @param targetKey
24 * @returns {any}
25 */
26export function getMetadata(metadataKey:string,target:any,targetKey?:string) {
27 return Reflect.getMetadata(metadataKey,target,targetKey)
28}
29
30export function makeMetadataGetter(metadataKey:string):(target:any,targetKey:string) => any {
31 return function(target:any,targetKey:string) {
32 return Reflect.getMetadata(metadataKey,target,targetKey)
33 }
34}
35
36export const getMetadataReturnType = makeMetadataGetter(ReturnTypeKey)
37export const getMetadataType = makeMetadataGetter(TypeKey)
38
39
40/**
41 * Property decorator types for the decorator and the
42 * factories used with simple metadata
43 */
44export type MetadataPropertyDecorator = (target:any,propertyKey:string,descriptor:TypedPropertyDescriptor<any>) => any
45export type MetadataPropertyDecoratorFactory<T> = (opts?:T) => MetadataPropertyDecorator
46
47
48/**
49 * Create a simple options decorator for things like finders
50 *
51 * @param metadataKey
52 * @param includeTargetKey
53 * @param customizerFn
54 * @returns {function(T=): function(any, string, TypedPropertyDescriptor<any>): undefined}
55 * - in the customizer, opts is mutable
56 */
57export function makeOptionsDecorator<T>(
58 metadataKey:string,
59 includeTargetKey:boolean = true,
60 customizerFn:(opts:T,target:any,targetKey:string) => any = null
61):MetadataPropertyDecoratorFactory<T> {
62 return (opts?:T) => {
63 opts = opts || {} as T
64 return (target:any,propertyKey:string,descriptor:TypedPropertyDescriptor<any>) => {
65
66 // If a customizer was provided then use it
67 // Pass all important items
68 // NOTE: opts it mutable
69 if (customizerFn)
70 customizerFn(opts,target,propertyKey)
71
72 setMetadata(metadataKey,opts,target,(includeTargetKey) ? propertyKey : undefined)
73 }
74 }
75}