52 lines
1.3 KiB
JavaScript
52 lines
1.3 KiB
JavaScript
// src/compose.ts
|
|
import { Context } from "./context.js";
|
|
var compose = (middleware, onError, onNotFound) => {
|
|
return (context, next) => {
|
|
let index = -1;
|
|
return dispatch(0);
|
|
async function dispatch(i) {
|
|
if (i <= index) {
|
|
throw new Error("next() called multiple times");
|
|
}
|
|
index = i;
|
|
let res;
|
|
let isError = false;
|
|
let handler;
|
|
if (middleware[i]) {
|
|
handler = middleware[i][0][0];
|
|
if (context instanceof Context) {
|
|
context.req.routeIndex = i;
|
|
}
|
|
} else {
|
|
handler = i === middleware.length && next || void 0;
|
|
}
|
|
if (!handler) {
|
|
if (context instanceof Context && context.finalized === false && onNotFound) {
|
|
res = await onNotFound(context);
|
|
}
|
|
} else {
|
|
try {
|
|
res = await handler(context, () => {
|
|
return dispatch(i + 1);
|
|
});
|
|
} catch (err) {
|
|
if (err instanceof Error && context instanceof Context && onError) {
|
|
context.error = err;
|
|
res = await onError(err, context);
|
|
isError = true;
|
|
} else {
|
|
throw err;
|
|
}
|
|
}
|
|
}
|
|
if (res && (context.finalized === false || isError)) {
|
|
context.res = res;
|
|
}
|
|
return context;
|
|
}
|
|
};
|
|
};
|
|
export {
|
|
compose
|
|
};
|