-
Notifications
You must be signed in to change notification settings - Fork 0
/
decorators.ts
98 lines (91 loc) · 2.43 KB
/
decorators.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { _register, MetadataScope, getReferenceMetadata } from "./common";
import { MemberMeta } from "./metadata";
/**
* Inject the indicated instance or value to the property or param in the class.
*
* @param { (string | symbol | new (...args: unknown[]) => {}) } injectableTarget
*
* @returns {(target: any, propertyKey: string, paramIndex?: number) => void}
*/
export function inject(injectableTarget: string): (target: any, propertyKey?: string, paramIndex?: number) => void;
export function inject(injectableTarget: symbol): (target: any, propertyKey?: string, paramIndex?: number) => void;
export function inject(injectableTarget: (new (...args: unknown[]) => {})): (target: any, propertyKey: string, paramIndex?: number) => void;
export function inject(injectableTarget: string | symbol | (new (...args: unknown[]) => {})) {
return (target: any, propertyKey?: string, paramIndex?: number) => {
const clazz = (!propertyKey && Number.isInteger(paramIndex) && target) || target.constructor;
let metadata = getReferenceMetadata(clazz);
if (!metadata) {
injectable()(clazz);
metadata = getReferenceMetadata(clazz);
}
const injectTarget = typeof injectableTarget === "string"
? injectableTarget : typeof injectableTarget === "symbol"
? injectableTarget : injectableTarget.name;
// decorator in method's param
if (propertyKey && paramIndex >= 0) {
_register({
target: clazz,
methods: new Map<string, MemberMeta[]>([
[
propertyKey,
[
{
target: injectTarget,
paramIndex,
key: propertyKey
}
]
]
])
});
}
// decorator in construct's param
if (!propertyKey && paramIndex >= 0) {
_register({
target: clazz,
constructParams: [
{
target: injectTarget,
paramIndex,
key: propertyKey
}
]
});
}
// decorator in class props
if (propertyKey && paramIndex === undefined) {
_register({
target: clazz,
propeties: [
{
target: injectTarget,
paramIndex,
key: propertyKey
}
]
});
}
}
}
export function injectable(name?: string | symbol) {
return (target: any) => {
_register({
target,
key: name,
isClass: true,
name: target.name
});
return target;
}
}
export function singleton(name?: string | symbol) {
return (target: any) => {
_register({
target,
scope: MetadataScope.singleton,
key: name,
isClass: true,
name: target.name
});
}
}