pipio
Version:
Chain functions together and handle a complex workflow
74 lines (73 loc) • 2.92 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.pipio = exports.Pipio = void 0;
const utils_1 = require("./utils");
class Pipio {
constructor(handlers) {
this.handlers = handlers;
}
/**
* Add a new middleware to the pipeline
* @param fn Middleware function
* @returns {Pipio} A new instance of the pipio with the handler setup
*/
use(fn) {
return new Pipio([...this.handlers, fn]);
}
/**
* Build the pipeline and create a callable function
* @param params Build-time parameters
* @returns The wrapper function of the pipeline
*/
build(params) {
return (...args) => __awaiter(this, void 0, void 0, function* () {
let output = args;
for (const fn of this.handlers) {
try {
// call the function with the previous call result
const handlerResult = fn(output);
// if handler returns a promise, the we need to wait,
// otherwise, we're good to go
if ((0, utils_1.isPromise)(handlerResult) === true) {
output = yield handlerResult;
}
else {
output = handlerResult;
}
}
catch (e) {
// user handles the error, pass the error to their handler
if (typeof (params === null || params === void 0 ? void 0 : params.onError) === 'function') {
return params === null || params === void 0 ? void 0 : params.onError(e);
}
// no handler found, throw error
throw e;
}
}
// no more item in the stack
if (this.handlers.length === 0) {
output = undefined;
}
return output;
});
}
}
exports.Pipio = Pipio;
/**
* pipio create factory
* @param fn Main middleware
* @returns {Pipio} A new instance of pipio with the first handler configured
*/
const pipio = (fn) => {
return new Pipio([fn]);
};
exports.pipio = pipio;