UNPKG

before-after-hook

Version:

asynchronous before/error/after hooks for internal functionality

47 lines (41 loc) 964 B
// @ts-check export function addHook(state, kind, name, hook) { const orig = hook; if (!state.registry[name]) { state.registry[name] = []; } if (kind === "before") { hook = (method, options) => { return Promise.resolve() .then(orig.bind(null, options)) .then(method.bind(null, options)); }; } if (kind === "after") { hook = (method, options) => { let result; return Promise.resolve() .then(method.bind(null, options)) .then((result_) => { result = result_; return orig(result, options); }) .then(() => { return result; }); }; } if (kind === "error") { hook = (method, options) => { return Promise.resolve() .then(method.bind(null, options)) .catch((error) => { return orig(error, options); }); }; } state.registry[name].push({ hook: hook, orig: orig, }); }