0
0
mirror of https://github.com/honojs/hono.git synced 2024-11-29 17:46:30 +01:00
hono/deno_dist/compose.ts

83 lines
2.3 KiB
TypeScript
Raw Normal View History

import { HonoContext } from './context.ts'
import type { Environment, NotFoundHandler, ErrorHandler } from './types.ts'
import type { Schema } from './validator/schema.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,
P extends string = string,
E extends Partial<Environment> = Environment,
D extends Partial<Schema> = Schema
>(
middleware: Function[],
onNotFound?: NotFoundHandler<P, E, D>,
onError?: ErrorHandler<P, E, D>
) => {
const middlewareLength = middleware.length
return (context: C, next?: Function) => {
2022-07-02 08:09:45 +02:00
let index = -1
return dispatch(0)
function dispatch(i: number): C | 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
}
let handler = middleware[i]
index = i
if (i === middlewareLength && next) handler = next
2022-07-02 08:09:45 +02:00
let res
let isError = false
2022-07-02 08:09:45 +02:00
if (!handler) {
if (context instanceof HonoContext && context.finalized === false && onNotFound) {
res = onNotFound(context)
2022-07-02 08:09:45 +02:00
}
} else {
try {
res = handler(context, () => {
const dispatchRes = dispatch(i + 1)
return dispatchRes instanceof Promise ? dispatchRes : Promise.resolve(dispatchRes)
})
} catch (err) {
if (err instanceof Error && context instanceof HonoContext && onError) {
context.error = err
res = onError(err, context)
isError = true
} else {
throw err
}
}
2022-07-02 08:09:45 +02:00
}
if (!(res instanceof Promise)) {
if (res && (context.finalized === false || isError)) {
context.res = res
}
return context
} else {
return res
.then((res) => {
if (res && context.finalized === false) {
context.res = res
}
return context
})
.catch((err) => {
if (err instanceof Error && context instanceof HonoContext && onError) {
context.error = err
context.res = onError(err, context)
return context
}
throw err
})
}
2022-07-02 08:09:45 +02:00
}
}
}