prepost
Version:
Alter arguments and return values before and after a function is called
53 lines (39 loc) • 1.47 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = post;
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var postCallNoop = function postCallNoop(res) {
return res;
};
// Alter the return value before it is passed back to the caller
function post() {
var _ref;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
// Flatten args so that pre functions can be passed as arrays
args = (_ref = []).concat.apply(_ref, _toConsumableArray(args));
if (args.length < 2) {
throw new Error('Two arguments required');
} else if (args.length > 2) {
args = [post.apply(undefined, _toConsumableArray(args.slice(0, -1))), args[args.length - 1]];
}
var callFn = args[0];
if (typeof callFn !== 'function') {
throw new TypeError('Function to call must be a function');
}
var postFn = args[1] || postCallNoop;
if (typeof postFn !== 'function') {
throw new TypeError('Post function must be a function');
}
return function () {
var res = callFn.apply(undefined, arguments);
// If res is a promise, resolve it before passing it to postFn
if (res && typeof res.then === 'function') {
return res.then(postFn);
}
return postFn(res);
};
}