compose.ts
This file
Path
src/compose.ts
73 lines · 2.2 KiB · TypeScript
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–73why, one step back1import type { Context } from './context'2import type { Env, ErrorHandler, Next, NotFoundHandler } from './types'34/**5 * Compose middleware functions into a single function based on `koa-compose` package.6 *7 * @template E - The environment type.8 *9 * @param {[[Function, unknown], unknown][] | [[Function]][]} middleware - An array of middleware functions and their corresponding parameters.10 * @param {ErrorHandler<E>} [onError] - An optional error handler function.11 * @param {NotFoundHandler<E>} [onNotFound] - An optional not-found handler function.12 *13 * @returns {(context: Context, next?: Next) => Promise<Context>} - A composed middleware function.14 */15export const compose = <E extends Env = Env>(16 middleware: [[Function, unknown], unknown][] | [[Function]][],17 onError?: ErrorHandler<E>,18 onNotFound?: NotFoundHandler<E>19): ((context: Context, next?: Next) => Promise<Context>) => {20 return (context, next) => {21 let index = -12223 return dispatch(0)2425 /**26 * Dispatch the middleware functions.27 *28 * @param {number} i - The current index in the middleware array.29 *30 * @returns {Promise<Context>} - A promise that resolves to the context.31 */32 async function dispatch(i: number): Promise<Context> {33 if (i <= index) {34 throw new Error('next() called multiple times')35 }36 index = i3738 let res39 let isError = false40 let handler4142 if (middleware[i]) {43 handler = middleware[i][0][0]44 context.req.routeIndex = i45 } else {46 handler = (i === middleware.length && next) || undefined47 }4849 if (handler) {50 try {51 res = await handler(context, () => dispatch(i + 1))52 } catch (err) {53 if (err instanceof Error && onError) {54 context.error = err55 res = await onError(err, context)56 isError = true57 } else {58 throw err59 }60 }61 } else {62 if (context.finalized === false && onNotFound) {63 res = await onNotFound(context)64 }65 }6667 if (res && (context.finalized === false || isError)) {68 context.res = res69 }70 return context71 }72 }73}