ufiber
Version:
Next-gen webserver for node-js developer
31 lines (29 loc) • 835 B
JavaScript
const require_consts = require('../consts.cjs');
//#region src/router/compose.ts
/**
* Compose multiple middleware functions into a single async callable function.
*/
const compose = (middleware, options) => (ctx, next) => {
const index = -1;
return dispatch(0);
async function dispatch(i) {
if (i <= index) throw new Error("next() called multiple times");
let handler;
if (middleware[i]) {
handler = middleware[i][0][0];
ctx[require_consts.kCtxReq].routeIndex = i;
} else handler = i === middleware.length && next || void 0;
if (!handler) {
if (options?.onNotFound) await options.onNotFound(ctx);
return;
}
try {
await handler(ctx, () => dispatch(i + 1));
} catch (err) {
if (options?.onError) await options.onError(err, ctx);
else throw err;
}
}
};
//#endregion
exports.compose = compose;