hooks: Asyncify mapFirst

This commit is contained in:
Richard Hansen 2021-01-31 16:51:37 -05:00 committed by John McLear
parent 0b83ff8ec2
commit 53ccfa8703

View file

@ -1,6 +1,7 @@
'use strict'; 'use strict';
const pluginDefs = require('./plugin_defs'); const pluginDefs = require('./plugin_defs');
const util = require('util');
// Maps the name of a server-side hook to a string explaining the deprecation // Maps the name of a server-side hook to a string explaining the deprecation
// (e.g., 'use the foo hook instead'). // (e.g., 'use the foo hook instead').
@ -48,19 +49,13 @@ const syncMapFirst = (hooks, fn) => {
return []; return [];
}; };
const mapFirst = (lst, fn, cb, predicate) => { const mapFirst = async (hooks, fn, predicate = null) => {
if (predicate == null) predicate = (x) => (x != null && x.length > 0); if (predicate == null) predicate = (val) => val.length;
let i = 0; for (const hook of hooks) {
const val = await fn(hook);
const next = () => { if (predicate(val)) return val;
if (i >= lst.length) return cb(null, []); }
fn(lst[i++], (err, result) => { return [];
if (err) return cb(err);
if (predicate(result)) return cb(null, result);
next();
});
};
next();
}; };
// Calls the hook function synchronously and returns the value provided by the hook function (via // Calls the hook function synchronously and returns the value provided by the hook function (via
@ -377,15 +372,9 @@ exports.callFirst = (hookName, context) => {
const aCallFirst = (hookName, context, cb, predicate) => { const aCallFirst = (hookName, context, cb, predicate) => {
if (!context) context = {}; if (!context) context = {};
if (!cb) cb = () => {}; if (!cb) cb = () => {};
if (pluginDefs.hooks[hookName] === undefined) return cb(null, []); const hooks = pluginDefs.hooks[hookName] || [];
mapFirst( const fn = async (hook) => await util.promisify(hookCallWrapper)(hook, hookName, context);
pluginDefs.hooks[hookName], util.callbackify(mapFirst)(hooks, fn, predicate, cb);
(hook, cb) => {
hookCallWrapper(hook, hookName, context, (res) => { cb(null, res); });
},
cb,
predicate
);
}; };
/* return a Promise if cb is not supplied */ /* return a Promise if cb is not supplied */