Files
SnowLuma/.pnpm-store/v11/files/46/ebf4321871570823a79529ce5b5eb9a79c83b2ab966e999b605d4b67cbae7257893f9b04a5e3614e42de9f074a0439dee6d311c2da6974879b3006c8816eb8
TanTan 2a69b23b47
Dev Build / cleanup (push) Canceled after 0s
Dev Build / typecheck (push) Canceled after 0s
Dev Build / build (linux-arm64, ubuntu-24.04-arm, linux-arm64) (push) Canceled after 0s
Dev Build / build (linux-x64, ubuntu-latest, linux-x64) (push) Canceled after 0s
Dev Build / build (win-x64, windows-latest, win32-x64) (push) Canceled after 0s
Dev Build / dispatch-dev-docker (push) Skipped
docs: 仓库链接指向本镜像仓库
2026-11-13 09:27:07 +08:00

51 lines
1.6 KiB
Plaintext

//#region src/compose.ts
/**
* Compose middleware functions into a single function based on `koa-compose` package.
*
* @template E - The environment type.
*
* @param {[[Function, unknown], unknown][] | [[Function]][]} middleware - An array of middleware functions and their corresponding parameters.
* @param {ErrorHandler<E>} [onError] - An optional error handler function.
* @param {NotFoundHandler<E>} [onNotFound] - An optional not-found handler function.
*
* @returns {(context: Context, next?: Next) => Promise<Context>} - A composed middleware function.
*/
const compose = (middleware, onError, onNotFound) => {
return (context, next) => {
let index = -1;
return dispatch(0);
/**
* Dispatch the middleware functions.
*
* @param {number} i - The current index in the middleware array.
*
* @returns {Promise<Context>} - A promise that resolves to the context.
*/
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];
context.req.routeIndex = i;
} else handler = i === middleware.length && next || void 0;
if (handler) try {
res = await handler(context, () => dispatch(i + 1));
} catch (err) {
if (err instanceof Error && onError) {
context.error = err;
res = await onError(err, context);
isError = true;
} else throw err;
}
else if (context.finalized === false && onNotFound) res = await onNotFound(context);
if (res && (context.finalized === false || isError)) context.res = res;
return context;
}
};
};
//#endregion
export { compose };