feat: hooks can now return promise or call callbacks

* hooks can now return promise or call callbacks, either way works

* cleanups

* moar cleanups and fix callback 1st null arg

* rm unnessesary spread
This commit is contained in:
Aziz Khoury
2019-06-10 19:05:27 +03:00
committed by Julian Lam
parent 376390c45f
commit a6436716ea
3 changed files with 118 additions and 20 deletions

View File

@@ -1,7 +1,8 @@
'use strict';
var winston = require('winston');
var async = require('async');
const winston = require('winston');
const async = require('async');
const utils = require('../utils');
module.exports = function (Plugins) {
Plugins.deprecatedHooks = {
@@ -132,8 +133,13 @@ module.exports = function (Plugins) {
}
return next(null, params);
}
hookObj.method(params, next);
const returned = hookObj.method(params, next);
if (utils.isPromise(returned)) {
returned.then(
payload => setImmediate(next, null, payload),
err => setImmediate(next, err)
);
}
}, callback);
}
@@ -160,26 +166,35 @@ module.exports = function (Plugins) {
}
async.each(hookList, function (hookObj, next) {
if (typeof hookObj.method === 'function') {
var timedOut = false;
var timeoutId = setTimeout(function () {
let timedOut = false;
const timeoutId = setTimeout(function () {
winston.warn('[plugins] Callback timed out, hook \'' + hook + '\' in plugin \'' + hookObj.id + '\'');
timedOut = true;
next();
}, 5000);
try {
hookObj.method(params, function () {
clearTimeout(timeoutId);
if (!timedOut) {
next.apply(null, arguments);
}
});
} catch (err) {
const onError = (err) => {
winston.error('[plugins] Error executing \'' + hook + '\' in plugin \'' + hookObj.id + '\'');
winston.error(err);
clearTimeout(timeoutId);
next();
};
const callback = (...args) => {
clearTimeout(timeoutId);
if (!timedOut) {
next(...args);
}
};
try {
const returned = hookObj.method(params, callback);
if (utils.isPromise(returned)) {
returned.then(
payload => setImmediate(callback, null, payload),
err => setImmediate(onError, err)
);
}
} catch (err) {
onError(err);
}
} else {
next();