Created
July 11, 2018 19:07
-
-
Save JaredCE/9beb2ece5ebb3bd160c018e1c8ff6221 to your computer and use it in GitHub Desktop.
I've been playing around with AOP in JavaScript to create a Logger that I can attach to classes and output what is going on (mainly instantiation, calling of functions and the results from functions). I've done this by creating a static class (static method in a class) that essentially is a factory that uses a proxy to trap the instantiation of …
This file contains hidden or 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
class Logger { | |
static ClassHandler(eventEmitter, obj) { | |
const InstanceHandler = { | |
get(target, prop, receiver){ | |
eventEmitter.publish(`${prop} called on ${target.constructor.name}`); | |
const orig = Reflect.get(target, prop, receiver); | |
if (typeof orig == "function" && | |
prop !== 'Logger') { | |
return function (...args) { | |
eventEmitter.publish(`Method ${prop} called with ${JSON.stringify(args)}`); | |
let result = orig.apply(this, args); | |
eventEmitter.publish(`Result from ${prop} is: ${JSON.stringify(result)}`); | |
return result; | |
}; | |
} else { | |
return orig; | |
} | |
} | |
} | |
const handler = { | |
construct(target, args) { | |
eventEmitter.publish(`${target.name} instantiated`); | |
const instance = Reflect.construct(...arguments); | |
return new Proxy(instance, InstanceHandler); | |
}, | |
apply(target, thisArg, argumentsList) { | |
eventEmitter.publish(`${target.name} called with with ${JSON.stringify(argumentsList)}`); | |
const result = Reflect.apply(...arguments); | |
eventEmitter.publish(`Result from ${target.name} is: ${JSON.stringify(result)}`); | |
return result; | |
}, | |
} | |
return new Proxy(obj, handler); | |
} | |
} | |
module.exports = Logger; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment