-
Notifications
You must be signed in to change notification settings - Fork 568
/
decoratorService.ts
279 lines (259 loc) · 9.06 KB
/
decoratorService.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import {
getClassMetadata,
Init,
Inject,
Provide,
Scope,
INJECT_CUSTOM_METHOD,
APPLICATION_CONTEXT_KEY,
INJECT_CUSTOM_PARAM,
getMethodParamTypes,
transformTypeFromTSDesign,
} from '../decorator';
import {
MethodDecoratorMetaData,
ParameterDecoratorMetaData,
HandlerFunction,
IMidwayContainer,
MethodHandlerFunction,
ParameterHandlerFunction,
JoinPoint,
ScopeEnum,
PipeUnionTransform,
PipeTransform,
} from '../interface';
import { MidwayAspectService } from './aspectService';
import { MidwayCommonError, MidwayParameterError } from '../error';
import * as util from 'util';
import { isClass } from '../util/types';
const debug = util.debuglog('midway:debug');
@Provide()
@Scope(ScopeEnum.Singleton)
export class MidwayDecoratorService {
private propertyHandlerMap = new Map<string, HandlerFunction>();
private methodDecoratorMap: Map<string, (...args) => any> = new Map();
private parameterDecoratorMap: Map<string, (...args) => any> = new Map();
private parameterDecoratorPipes: Map<string, PipeUnionTransform[]> =
new Map();
@Inject()
private aspectService: MidwayAspectService;
constructor(readonly applicationContext: IMidwayContainer) {}
@Init()
protected init() {
// add custom method decorator listener
this.applicationContext.onBeforeBind(Clzz => {
// find custom method decorator metadata, include method decorator information array
const methodDecoratorMetadataList: MethodDecoratorMetaData[] =
getClassMetadata(INJECT_CUSTOM_METHOD, Clzz);
if (methodDecoratorMetadataList) {
// loop it, save this order for decorator run
for (const meta of methodDecoratorMetadataList) {
const { propertyName, key, metadata, options } = meta;
if (!options || !options.impl) {
continue;
}
// add aspect implementation first
this.aspectService.interceptPrototypeMethod(
Clzz,
propertyName,
() => {
const methodDecoratorHandler = this.methodDecoratorMap.get(key);
if (!methodDecoratorHandler) {
throw new MidwayCommonError(
`Method Decorator "${key}" handler not found, please register first.`
);
}
return methodDecoratorHandler({
target: Clzz,
propertyName,
metadata,
});
}
);
}
}
// find custom param decorator metadata
const parameterDecoratorMetadata: {
[methodName: string]: Array<ParameterDecoratorMetaData>;
} = getClassMetadata(INJECT_CUSTOM_PARAM, Clzz);
if (parameterDecoratorMetadata) {
// loop it, save this order for decorator run
for (const methodName of Object.keys(parameterDecoratorMetadata)) {
// add aspect implementation first
this.aspectService.interceptPrototypeMethod(Clzz, methodName, () => {
return {
before: async (joinPoint: JoinPoint) => {
// joinPoint.args
const newArgs = [...joinPoint.args];
for (const meta of parameterDecoratorMetadata[methodName]) {
const {
propertyName,
key,
metadata,
parameterIndex,
options,
} = meta;
let parameterDecoratorHandler;
if (options && options.impl) {
parameterDecoratorHandler =
this.parameterDecoratorMap.get(key);
if (!parameterDecoratorHandler) {
throw new MidwayCommonError(
`Parameter Decorator "${key}" handler not found, please register first.`
);
}
} else {
// set default handler
parameterDecoratorHandler = async ({
parameterIndex,
originArgs,
}) => {
return originArgs[parameterIndex];
};
}
const paramTypes = getMethodParamTypes(Clzz, propertyName);
let skipPipes = false;
try {
newArgs[parameterIndex] = await parameterDecoratorHandler({
metadata,
propertyName,
parameterIndex,
target: Clzz,
originArgs: newArgs,
originParamType: paramTypes[parameterIndex],
instance: joinPoint.target,
});
} catch (err) {
skipPipes = true;
if (options?.throwError === true) {
throw err;
} else {
// ignore
debug(
`[core]: Parameter decorator throw error and use origin args, ${err.stack}`
);
}
}
if (skipPipes) {
continue;
}
const pipes = [
...(this.parameterDecoratorPipes.get(key) || []),
...(options?.pipes || []),
];
for (const pipe of pipes) {
let transform;
if ('transform' in pipe) {
transform = pipe['transform'].bind(pipe);
} else if (isClass(pipe)) {
const ins =
await this.applicationContext.getAsync<PipeTransform>(
pipe as any
);
transform = ins.transform.bind(ins);
} else if (typeof pipe === 'function') {
transform = pipe;
} else {
throw new MidwayParameterError(
'Pipe must be a function or implement PipeTransform interface'
);
}
newArgs[parameterIndex] = await transform(
newArgs[parameterIndex],
{
metaType: transformTypeFromTSDesign(
paramTypes[parameterIndex]
),
metadata,
target: joinPoint.target,
methodName: joinPoint.methodName,
}
);
}
}
joinPoint.args = newArgs;
},
};
});
}
}
});
// add custom property decorator listener
this.applicationContext.onObjectCreated((instance, options) => {
if (
this.propertyHandlerMap.size > 0 &&
Array.isArray(options.definition.handlerProps)
) {
// has bind in container
for (const item of options.definition.handlerProps) {
this.defineGetterPropertyValue(
item,
instance,
this.getHandler(item.key)
);
}
}
});
// register @ApplicationContext
this.registerPropertyHandler(
APPLICATION_CONTEXT_KEY,
(propertyName, mete) => {
return this.applicationContext;
}
);
}
public registerPropertyHandler(decoratorKey: string, fn: HandlerFunction) {
debug(`[core]: Register property decorator key="${decoratorKey}"`);
this.propertyHandlerMap.set(decoratorKey, fn);
}
public registerMethodHandler(
decoratorKey: string,
fn: MethodHandlerFunction
) {
debug(`[core]: Register method decorator key="${decoratorKey}"`);
this.methodDecoratorMap.set(decoratorKey, fn);
}
public registerParameterHandler(
decoratorKey: string,
fn: ParameterHandlerFunction
) {
debug(`[core]: Register parameter decorator key="${decoratorKey}"`);
this.parameterDecoratorMap.set(decoratorKey, fn);
}
public registerParameterPipes(
decoratorKey: string,
pipes: PipeUnionTransform[]
) {
if (!this.parameterDecoratorPipes.has(decoratorKey)) {
this.parameterDecoratorPipes.set(decoratorKey, []);
}
this.parameterDecoratorPipes.set(
decoratorKey,
this.parameterDecoratorPipes.get(decoratorKey).concat(pipes)
);
}
/**
* binding getter method for decorator
*
* @param prop
* @param instance
* @param getterHandler
*/
private defineGetterPropertyValue(prop, instance, getterHandler) {
if (prop && getterHandler) {
if (prop.propertyName) {
Object.defineProperty(instance, prop.propertyName, {
get: () =>
getterHandler(prop.propertyName, prop.metadata ?? {}, instance),
configurable: true, // 继承对象有可能会有相同属性,这里需要配置成 true
enumerable: true,
});
}
}
}
private getHandler(key: string) {
if (this.propertyHandlerMap.has(key)) {
return this.propertyHandlerMap.get(key);
}
}
}