2022-07-10 16:44:23 +02:00
|
|
|
import { HonoContext } from './context.ts'
|
2022-07-02 08:09:45 +02:00
|
|
|
import type { ErrorHandler, NotFoundHandler } from './hono.ts'
|
|
|
|
|
|
|
|
// Based on the code in the MIT licensed `koa-compose` package.
|
|
|
|
export const compose = <C>(
|
|
|
|
middleware: Function[],
|
|
|
|
onError?: ErrorHandler,
|
|
|
|
onNotFound?: NotFoundHandler
|
|
|
|
) => {
|
2022-08-09 03:51:08 +02:00
|
|
|
const middlewareLength = middleware.length
|
2022-07-17 02:13:44 +02:00
|
|
|
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> {
|
|
|
|
if (i <= index) {
|
|
|
|
return Promise.reject(new Error('next() called multiple times'))
|
|
|
|
}
|
|
|
|
let handler = middleware[i]
|
|
|
|
index = i
|
2022-08-09 03:51:08 +02:00
|
|
|
if (i === middlewareLength && next) handler = next
|
2022-07-02 08:09:45 +02:00
|
|
|
|
|
|
|
if (!handler) {
|
2022-07-10 16:44:23 +02:00
|
|
|
if (context instanceof HonoContext && context.finalized === false && onNotFound) {
|
2022-07-02 08:09:45 +02:00
|
|
|
context.res = await onNotFound(context)
|
|
|
|
}
|
|
|
|
return Promise.resolve(context)
|
|
|
|
}
|
|
|
|
|
|
|
|
return Promise.resolve(handler(context, () => dispatch(i + 1)))
|
2022-07-17 02:13:44 +02:00
|
|
|
.then((res: Response) => {
|
2022-07-02 08:09:45 +02:00
|
|
|
// If handler return Response like `return c.text('foo')`
|
2022-07-10 16:44:23 +02:00
|
|
|
if (res && context instanceof HonoContext) {
|
2022-07-02 08:09:45 +02:00
|
|
|
context.res = res
|
|
|
|
}
|
|
|
|
return context
|
|
|
|
})
|
|
|
|
.catch((err) => {
|
2022-07-10 16:44:23 +02:00
|
|
|
if (context instanceof HonoContext && onError) {
|
2022-07-02 08:09:45 +02:00
|
|
|
if (err instanceof Error) {
|
|
|
|
context.res = onError(err, context)
|
|
|
|
}
|
|
|
|
return context
|
|
|
|
} else {
|
|
|
|
throw err
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|