forked from NodeBB/NodeBB
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromisify.js
More file actions
61 lines (52 loc) · 1.52 KB
/
Copy pathpromisify.js
File metadata and controls
61 lines (52 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
'use strict';
const util = require('util');
module.exports = function (theModule, ignoreKeys) {
ignoreKeys = ignoreKeys || [];
function isCallbackedFunction(func) {
if (typeof func !== 'function') {
return false;
}
const str = func.toString().split('\n')[0];
return str.includes('callback)');
}
function isAsyncFunction(fn) {
return fn && fn.constructor && fn.constructor.name === 'AsyncFunction';
}
function promisifyRecursive(module) {
if (!module) {
return;
}
const keys = Object.keys(module);
keys.forEach((key) => {
if (ignoreKeys.includes(key)) {
return;
}
if (isAsyncFunction(module[key])) {
module[key] = wrapCallback(module[key], util.callbackify(module[key]));
} else if (isCallbackedFunction(module[key])) {
module[key] = wrapPromise(module[key], util.promisify(module[key]));
} else if (typeof module[key] === 'object') {
promisifyRecursive(module[key]);
}
});
}
function wrapCallback(origFn, callbackFn) {
return async function wrapperCallback(...args) {
if (args.length && typeof args[args.length - 1] === 'function') {
const cb = args.pop();
args.push((err, res) => (res !== undefined ? cb(err, res) : cb(err)));
return callbackFn(...args);
}
return origFn(...args);
};
}
function wrapPromise(origFn, promiseFn) {
return function wrapperPromise(...args) {
if (args.length && typeof args[args.length - 1] === 'function') {
return origFn(...args);
}
return promiseFn(...args);
};
}
promisifyRecursive(theModule);
};