Created
April 10, 2021 15:32
-
-
Save neomatrixcode/b0baaf460ad596bc127a35b1688883a3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Helping function used to get all methods of an object */ | |
const getMethods = (obj) => Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(item => typeof obj[item] === 'function') | |
/** Replace the original method with a custom function that will call our aspect when the advice dictates */ | |
function replaceMethod(target, methodName, aspect, advice) { | |
const originalCode = target[methodName] | |
target[methodName] = (...args) => { | |
if(["before", "around"].includes(advice)) { | |
aspect.apply(target, args) | |
} | |
const returnedValue = originalCode.apply(target, args) | |
if(["after", "around"].includes(advice)) { | |
aspect.apply(target, args) | |
} | |
if("afterReturning" == advice) { | |
return aspect.apply(target, [returnedValue]) | |
} else { | |
return returnedValue | |
} | |
} | |
} | |
//inject the aspect on our target when and where we need to | |
const inject = (target, aspect, advice, pointcut, method = null) => { | |
if(pointcut == "method") { | |
if(method != null) { | |
replaceMethod(target, method, aspect, advice) | |
} else { | |
throw new Error("Tryin to add an aspect to a method, but no method specified") | |
} | |
} | |
if(pointcut == "methods") { | |
const methods = getMethods(target) | |
methods.forEach( m => { | |
replaceMethod(target, m, aspect, advice) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment