Skip to content

Instantly share code, notes, and snippets.

@JosePedroDias
Last active July 11, 2017 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JosePedroDias/8ac8ea3669a565fa3514df9bec2d77ae to your computer and use it in GitHub Desktop.
Save JosePedroDias/8ac8ea3669a565fa3514df9bec2d77ae to your computer and use it in GitHub Desktop.
before and after hooks for api methods
'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}`);
@JosePedroDias
Copy link
Author

DYI spy. Of course this isn't performant. Skip toArr() call or args passing altogether if you're not using it.

@JosePedroDias
Copy link
Author

You can try it out here:
http://jsbin.com/cabekuz/edit?js,console

@JosePedroDias
Copy link
Author

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