diff --git a/index.js b/index.js new file mode 100644 index 0000000..2a3c741 --- /dev/null +++ b/index.js @@ -0,0 +1,42 @@ +'use strict' +function _callFunc(self, obj, args){ + const fn = typeof obj === 'function' ? obj : obj.function + if(typeof fn !== 'function') { + return + } + let functionArguments = obj.args + const context = obj.ignoreContext ? undefined : self + if(!functionArguments){ + functionArguments = Array.from(args) + } + if(typeof functionArguments === 'object' && functionArguments.constructor === Array) { + fn.apply(context, functionArguments) + } +} + +function overrideFunction(self, functionToReplace, {before, after}) { + const oldFunc = self[functionToReplace] + if(typeof oldFunc !== 'function'){ + throw new Error('Original function not provided') + } + const newFunc = function(...args){ + _callFunc(self, before, args) + oldFunc.apply(self, args) + _callFunc(self, after, args) + } + self[functionToReplace] = newFunc + return newFunc +} + +if(typeof module !== 'undefined' && module.exports){ + module.exports = overrideFunction +} else if (typeof define === 'function' && define.amd) { + define(function () { + return config; + }); +} else { + global = (function () { + return this || (0, eval)('this'); + }()); + global.overrideFunction = overrideFunction +} \ No newline at end of file diff --git a/test.js b/test.js new file mode 100644 index 0000000..e038d21 --- /dev/null +++ b/test.js @@ -0,0 +1,23 @@ +'use strict' +const functionOverride = require('./index') + +const res = { + send: function(...args){ + console.log(`res.send called with arguments -- ${args} -- and context ${JSON.stringify(this)}`) + }, + a: 1 +} + +function before(...args){ + console.log(`before called with arguments -- ${args} -- and context ${JSON.stringify(this)}`) +} + +function after(...args) { + console.log(`after called with arguments -- ${args} -- and context ${JSON.stringify(this)}`) +} + +before = before.bind(this, "before", "fdsfsdfdsfsdfdsfds") + +res.send = functionOverride(res, 'send', {before, after}) + +res.send("dsa", "sfds") \ No newline at end of file