2021-06-04 22:19:14 +08:00
|
|
|
module.exports = addHook;
|
2021-02-08 12:58:32 +08:00
|
|
|
|
2021-06-04 22:19:14 +08:00
|
|
|
function addHook(state, kind, name, hook) {
|
|
|
|
var orig = hook;
|
2021-02-08 12:58:32 +08:00
|
|
|
if (!state.registry[name]) {
|
2021-06-04 22:19:14 +08:00
|
|
|
state.registry[name] = [];
|
2021-02-08 12:58:32 +08:00
|
|
|
}
|
|
|
|
|
2021-06-04 22:19:14 +08:00
|
|
|
if (kind === "before") {
|
2021-02-08 12:58:32 +08:00
|
|
|
hook = function (method, options) {
|
|
|
|
return Promise.resolve()
|
|
|
|
.then(orig.bind(null, options))
|
2021-06-04 22:19:14 +08:00
|
|
|
.then(method.bind(null, options));
|
|
|
|
};
|
2021-02-08 12:58:32 +08:00
|
|
|
}
|
|
|
|
|
2021-06-04 22:19:14 +08:00
|
|
|
if (kind === "after") {
|
2021-02-08 12:58:32 +08:00
|
|
|
hook = function (method, options) {
|
2021-06-04 22:19:14 +08:00
|
|
|
var result;
|
2021-02-08 12:58:32 +08:00
|
|
|
return Promise.resolve()
|
|
|
|
.then(method.bind(null, options))
|
|
|
|
.then(function (result_) {
|
2021-06-04 22:19:14 +08:00
|
|
|
result = result_;
|
|
|
|
return orig(result, options);
|
2021-02-08 12:58:32 +08:00
|
|
|
})
|
|
|
|
.then(function () {
|
2021-06-04 22:19:14 +08:00
|
|
|
return result;
|
|
|
|
});
|
|
|
|
};
|
2021-02-08 12:58:32 +08:00
|
|
|
}
|
|
|
|
|
2021-06-04 22:19:14 +08:00
|
|
|
if (kind === "error") {
|
2021-02-08 12:58:32 +08:00
|
|
|
hook = function (method, options) {
|
|
|
|
return Promise.resolve()
|
|
|
|
.then(method.bind(null, options))
|
|
|
|
.catch(function (error) {
|
2021-06-04 22:19:14 +08:00
|
|
|
return orig(error, options);
|
|
|
|
});
|
|
|
|
};
|
2021-02-08 12:58:32 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
state.registry[name].push({
|
|
|
|
hook: hook,
|
2021-06-04 22:19:14 +08:00
|
|
|
orig: orig,
|
|
|
|
});
|
2021-02-08 12:58:32 +08:00
|
|
|
}
|