0
0
mirror of https://github.com/honojs/hono.git synced 2024-11-29 09:43:20 +01:00
hono/deno_dist/compose.ts

66 lines
1.7 KiB
TypeScript
Raw Normal View History

import { Context } from './context.ts'
import type { ParamIndexMap, Params } from './router.ts'
import type { Env, NotFoundHandler, ErrorHandler } from './types.ts'
2022-07-02 08:09:45 +02:00
interface ComposeContext {
finalized: boolean
res: unknown
}
2022-07-02 08:09:45 +02:00
// Based on the code in the MIT licensed `koa-compose` package.
export const compose = <C extends ComposeContext, E extends Env = Env>(
middleware: [[Function, unknown], ParamIndexMap | Params][],
2023-02-09 11:49:27 +01:00
onError?: ErrorHandler<E>,
onNotFound?: NotFoundHandler<E>
) => {
return (context: C, next?: Function) => {
2022-07-02 08:09:45 +02:00
let index = -1
return dispatch(0)
async function dispatch(i: number): Promise<C> {
2022-07-02 08:09:45 +02:00
if (i <= index) {
throw new Error('next() called multiple times')
2022-07-02 08:09:45 +02:00
}
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) || undefined
}
2022-07-02 08:09:45 +02:00
if (!handler) {
if (context instanceof Context && context.finalized === false && onNotFound) {
res = await onNotFound(context)
2022-07-02 08:09:45 +02:00
}
} 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
}
}
2022-07-02 08:09:45 +02:00
}
if (res && (context.finalized === false || isError)) {
context.res = res
}
return context
2022-07-02 08:09:45 +02:00
}
}
}