47 lines
1004 B
JavaScript
Raw Normal View History

2023-10-25 14:27:07 -06:00
module.exports = addHook;
2022-11-03 10:55:07 -06:00
2023-10-25 14:27:07 -06:00
function addHook(state, kind, name, hook) {
var orig = hook;
2022-11-03 10:55:07 -06:00
if (!state.registry[name]) {
2023-10-25 14:27:07 -06:00
state.registry[name] = [];
2022-11-03 10:55:07 -06:00
}
2023-10-25 14:27:07 -06:00
if (kind === "before") {
2022-11-03 10:55:07 -06:00
hook = function (method, options) {
return Promise.resolve()
.then(orig.bind(null, options))
2023-10-25 14:27:07 -06:00
.then(method.bind(null, options));
};
2022-11-03 10:55:07 -06:00
}
2023-10-25 14:27:07 -06:00
if (kind === "after") {
2022-11-03 10:55:07 -06:00
hook = function (method, options) {
2023-10-25 14:27:07 -06:00
var result;
2022-11-03 10:55:07 -06:00
return Promise.resolve()
.then(method.bind(null, options))
.then(function (result_) {
2023-10-25 14:27:07 -06:00
result = result_;
return orig(result, options);
2022-11-03 10:55:07 -06:00
})
.then(function () {
2023-10-25 14:27:07 -06:00
return result;
});
};
2022-11-03 10:55:07 -06:00
}
2023-10-25 14:27:07 -06:00
if (kind === "error") {
2022-11-03 10:55:07 -06:00
hook = function (method, options) {
return Promise.resolve()
.then(method.bind(null, options))
.catch(function (error) {
2023-10-25 14:27:07 -06:00
return orig(error, options);
});
};
2022-11-03 10:55:07 -06:00
}
state.registry[name].push({
hook: hook,
2023-10-25 14:27:07 -06:00
orig: orig,
});
2022-11-03 10:55:07 -06:00
}