|
| 1 | +import { CrosscutAdviceFactory } from './CrosscutAdviceFactory'; |
| 2 | +import { EggProtoImplClass } from '@eggjs/core-decorator'; |
| 3 | +import { Aspect, AspectBuilder } from './model/Aspect'; |
| 4 | +import { PointcutAdviceInfoUtil } from './util/PointcutAdviceInfoUtil'; |
| 5 | + |
| 6 | +export class AspectMetaBuilder { |
| 7 | + private readonly clazz: EggProtoImplClass; |
| 8 | + private readonly crosscutAdviceFactory: CrosscutAdviceFactory; |
| 9 | + |
| 10 | + constructor(clazz: EggProtoImplClass, options: { |
| 11 | + crosscutAdviceFactory: CrosscutAdviceFactory; |
| 12 | + }) { |
| 13 | + this.clazz = clazz; |
| 14 | + this.crosscutAdviceFactory = options.crosscutAdviceFactory; |
| 15 | + } |
| 16 | + |
| 17 | + build(): Array<Aspect> { |
| 18 | + const aspectList: Array<Aspect> = []; |
| 19 | + const methods = AspectMetaBuilder.getAllMethods(this.clazz); |
| 20 | + for (const method of methods) { |
| 21 | + const aspect = this.doBuildMethodAspect(method); |
| 22 | + if (aspect) { |
| 23 | + aspectList.push(aspect); |
| 24 | + } |
| 25 | + } |
| 26 | + return aspectList; |
| 27 | + } |
| 28 | + |
| 29 | + private static getAllMethods(clazz): PropertyKey[] { |
| 30 | + const methodSet = new Set<string>(); |
| 31 | + function getMethods(obj) { |
| 32 | + if (obj) { |
| 33 | + const names = Object.getOwnPropertyNames(obj); |
| 34 | + for (const name of names) { |
| 35 | + if (obj[name] instanceof Function) { |
| 36 | + methodSet.add(name); |
| 37 | + } |
| 38 | + } |
| 39 | + getMethods(Object.getPrototypeOf(obj)); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + getMethods(clazz.prototype); |
| 44 | + |
| 45 | + return Array.from(methodSet); |
| 46 | + } |
| 47 | + |
| 48 | + private doBuildMethodAspect(method: PropertyKey): Aspect | undefined { |
| 49 | + const crosscutAdviceList = this.crosscutAdviceFactory.getAdvice(this.clazz, method); |
| 50 | + // decorator execute in reverse order |
| 51 | + const pointcutAdviceList = PointcutAdviceInfoUtil.getPointcutAdviceInfoList(this.clazz, method); |
| 52 | + if (!crosscutAdviceList.length && !pointcutAdviceList.length) return; |
| 53 | + const aspectBuilder = new AspectBuilder(this.clazz, method); |
| 54 | + for (const advice of crosscutAdviceList) { |
| 55 | + aspectBuilder.addAdvice(advice); |
| 56 | + } |
| 57 | + for (const advice of pointcutAdviceList) { |
| 58 | + aspectBuilder.addAdvice(advice); |
| 59 | + } |
| 60 | + return aspectBuilder.build(); |
| 61 | + } |
| 62 | +} |
0 commit comments