0
0
mirror of https://github.com/honojs/hono.git synced 2024-12-01 11:51:01 +01:00
hono/deno_dist/compose.ts
Yusuke Wada d3ff952599
fix(compose): do not handle the error in compose (#491)
* fix(compose): do not handle the error in `compose`

* tweak
2022-08-31 17:49:01 +09:00

36 lines
1.1 KiB
TypeScript

import { HonoContext } from './context.ts'
import type { NotFoundHandler } from './hono.ts'
// Based on the code in the MIT licensed `koa-compose` package.
export const compose = <C>(middleware: Function[], onNotFound?: NotFoundHandler) => {
const middlewareLength = middleware.length
return (context: C, next?: Function) => {
let index = -1
return dispatch(0)
async function dispatch(i: number): Promise<C> {
if (i <= index) {
throw new Error('next() called multiple times')
}
let handler = middleware[i]
index = i
if (i === middlewareLength && next) handler = next
if (!handler) {
if (context instanceof HonoContext && context.finalized === false && onNotFound) {
context.res = await onNotFound(context)
}
return context
}
const tmp = handler(context, () => dispatch(i + 1))
const res = tmp instanceof Promise ? await tmp : tmp
if (res && context instanceof HonoContext && context.finalized === false) {
context.res = res
}
return context
}
}
}