Last active
July 11, 2017 12:51
-
-
Save JosePedroDias/8ac8ea3669a565fa3514df9bec2d77ae to your computer and use it in GitHub Desktop.
before and after hooks for api methods
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
'use strict'; | |
// call something before the method(s) | |
function toArr(arrLike) { | |
return Array.prototype.slice.apply(arrLike); | |
} | |
function beforeMethod(parent, methodName, beforeFn) { | |
const oldFn = parent[methodName]; | |
parent[methodName] = function() { | |
const args = toArr(arguments) | |
beforeFn(methodName, args); | |
return oldFn.apply(parent, args); | |
}; | |
} | |
function afterMethod(parent, methodName, afterFn) { | |
const oldFn = parent[methodName]; | |
parent[methodName] = function() { | |
const args = toArr(arguments) | |
const res = oldFn.apply(parent, args); | |
afterFn(methodName, args, res); | |
return res; | |
}; | |
} | |
// object with method we want to listen to | |
const api = { | |
f1: function(a, b) { | |
return a + b; | |
} | |
} | |
// annotate | |
function before(methodName, args) { | |
console.warn(`method:%s, args:%s`, methodName, JSON.stringify(args)); | |
} | |
beforeMethod(api, 'f1', before); | |
function after(methodName, args, res) { | |
console.warn(`method:%s, args:%s, result:%s`, methodName, JSON.stringify(args), JSON.stringify(res)); | |
} | |
afterMethod(api, 'f1', after); | |
// stuff | |
const a = 2; | |
const b = 3; | |
const c = api.f1(a, b); | |
console.log(`f1(${a}, ${b}) = ${c}`); |
You can try it out here:
http://jsbin.com/cabekuz/edit?js,console
Example use case: when you can't use a debugger statement but can print a stacktrace..., use console.warn()
in a beforeMethod()
to understand who's calling it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
DYI spy. Of course this isn't performant. Skip
toArr()
call or args passing altogether if you're not using it.