compose.ts
This file
Path
src/compose.ts
73 lines 路 2.2 KiB 路 TypeScript
Last changed by
Not known.
History of this fileTake it
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import type { Context } from './context'import type { Env, ErrorHandler, Next, NotFoundHandler } from './types'
/** * 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. */export const compose = <E extends Env = Env>( middleware: [[Function, unknown], unknown][] | [[Function]][], onError?: ErrorHandler<E>, onNotFound?: NotFoundHandler<E>): ((context: Context, next?: Next) => Promise<Context>) => { 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: number): Promise<Context> { 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) || undefined }
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 } }}