UNPKG

call-hooks

Version:

Function for adding before/after/call/arguments/result hooks to another function.

47 lines (46 loc) 1.4 kB
/* IMPORT */ /* MAIN */ const callHooks = (fn, hooks) => { /* HELPERS */ const onCall = (args, thisArg) => { if (hooks.call) return hooks.call.call(thisArg, args); return fn.apply(thisArg, args); }; const onResult = (args, result) => { result = hooks.result ? hooks.result(args, result) : result; if (hooks.after) hooks.after(args, result); return result; }; const onError = (args, error) => { if (hooks.after) hooks.after(args, error); throw error; }; /* WRAPPER */ return function callHooksWrapper() { const argsv = Array.from(arguments); const args = hooks.args ? hooks.args(argsv) : argsv; if (hooks.before) hooks.before(args); if (!hooks.after && !hooks.result) return onCall(args, this); try { const result = onCall(args, this); if (result instanceof Promise) { const onResolve = (result) => onResult(args, result); const onReject = (error) => onError(args, error); return result.then(onResolve, onReject); } else { return onResult(args, result); } } catch (error) { onError(args, error); } }; //TSC }; /* EXPORT */ export default callHooks;