|
| 1 | +/** |
| 2 | + * This function generator generates a class method decorator, that calls a function before the |
| 3 | + * class method gets called. |
| 4 | + * |
| 5 | + * @example |
| 6 | + * ```ts |
| 7 | + * const RunBefore = genCallBefore<Foo>((instance) => { |
| 8 | + * if (instance.logging) { |
| 9 | + * console.log('Run before method call!'); |
| 10 | + * } |
| 11 | + * }); |
| 12 | + * |
| 13 | + * class Foo { |
| 14 | + * public logging : boolean; |
| 15 | + * |
| 16 | + * constructor() { |
| 17 | + * this.logging = false; |
| 18 | + * } |
| 19 | + * |
| 20 | + * public enableLogging() { |
| 21 | + * this.logging = true; |
| 22 | + * } |
| 23 | + * |
| 24 | + * @RunBefore |
| 25 | + * public hello() { |
| 26 | + * console.log('Hello'); |
| 27 | + * } |
| 28 | + * } |
| 29 | + * |
| 30 | + * const logger = new Foo(); |
| 31 | + * |
| 32 | + * logger.hello(); |
| 33 | + * // Hello |
| 34 | + * logger.enableLogging(); |
| 35 | + * logger.hello(); |
| 36 | + * // Run before method call! |
| 37 | + * // Hello |
| 38 | + * ``` |
| 39 | + * @param callbackFn Function to call before class method |
| 40 | + * @returns The decorator function. |
| 41 | + */ |
| 42 | +export function genCallBefore<Class>( |
| 43 | + callbackFn : (instance : Class, ...args : Array<unknown>) => void |
| 44 | +) : < |
| 45 | + MethodArguments extends Array<unknown>, |
| 46 | + MethodReturn extends unknown |
| 47 | +>( |
| 48 | + method : (this: Class, ...args : MethodArguments) => MethodReturn, |
| 49 | + _context : ClassMethodDecoratorContext< |
| 50 | + Class, |
| 51 | + (this : Class, ...args : MethodArguments) => MethodReturn |
| 52 | + > |
| 53 | +) => (this : Class, ...args : MethodArguments) => MethodReturn { |
| 54 | + return function callBefore< |
| 55 | + MethodArguments extends Array<unknown>, |
| 56 | + MethodReturn extends unknown |
| 57 | + >( |
| 58 | + method : (this : Class, ...args : MethodArguments) => MethodReturn, |
| 59 | + _context : ClassMethodDecoratorContext< |
| 60 | + Class, |
| 61 | + (this : Class, ...args : MethodArguments) => MethodReturn |
| 62 | + > |
| 63 | + ) : (this : Class, ...args : MethodArguments) => MethodReturn { |
| 64 | + return function decorator(this : Class, ...args : MethodArguments) : MethodReturn { |
| 65 | + callbackFn(this, ...args); |
| 66 | + return method.call(this, ...args); |
| 67 | + }; |
| 68 | + }; |
| 69 | +} |
0 commit comments