|
| 1 | +const { performance } = require('perf_hooks'); |
| 2 | + |
1 | 3 | /** |
2 | 4 | * Caches the result of the first execution of the method and returns it whenever it is called instead of executing it again. |
3 | 5 | * Works with methods and getters. |
@@ -83,3 +85,49 @@ export function exported(moduleName: string): any { |
83 | 85 | return descriptor; |
84 | 86 | }; |
85 | 87 | } |
| 88 | + |
| 89 | +export function performanceLog(injector?: IInjector): any { |
| 90 | + injector = injector || $injector; |
| 91 | + return function (target: any, propertyKey: string, descriptor: PropertyDescriptor): any { |
| 92 | + const originalMethod = descriptor.value; |
| 93 | + const className = target.constructor.name; |
| 94 | + const trackName = `${className}.${propertyKey}`; |
| 95 | + const performanceService: IPerformanceService = injector.resolve("performanceService"); |
| 96 | + |
| 97 | + //needed for the returned function to have the same name as the original - used in hooks decorator |
| 98 | + const tempObject = { |
| 99 | + [originalMethod.name]: function (...args: Array<any>) { |
| 100 | + const start = performance.now(); |
| 101 | + const result = originalMethod.apply(this, args); |
| 102 | + const resolvedPromise = Promise.resolve(result); |
| 103 | + let end; |
| 104 | + |
| 105 | + if (resolvedPromise !== result) { |
| 106 | + end = performance.now(); |
| 107 | + performanceService.processExecutionData(trackName, start, end, args); |
| 108 | + } else { |
| 109 | + resolvedPromise |
| 110 | + .then(() => { |
| 111 | + end = performance.now(); |
| 112 | + performanceService.processExecutionData(trackName, start, end, args); |
| 113 | + }) |
| 114 | + .catch((err) => { |
| 115 | + end = performance.now(); |
| 116 | + performanceService.processExecutionData(trackName, start, end, args); |
| 117 | + }); |
| 118 | + |
| 119 | + } |
| 120 | + |
| 121 | + return result; |
| 122 | + } |
| 123 | + } |
| 124 | + descriptor.value = tempObject[originalMethod.name] |
| 125 | + |
| 126 | + // used to get parameter names in hooks decorator |
| 127 | + descriptor.value.toString = () => { |
| 128 | + return originalMethod.toString(); |
| 129 | + }; |
| 130 | + |
| 131 | + return descriptor; |
| 132 | + }; |
| 133 | +} |
0 commit comments