-
-
Notifications
You must be signed in to change notification settings - Fork 443
/
compose.ts
48 lines (45 loc) · 1.43 KB
/
compose.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { HonoContext } from './context.ts'
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
) => {
return (context: C, next?: Function) => {
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
if (i === middleware.length && next) handler = next
if (!handler) {
if (context instanceof HonoContext && context.finalized === false && onNotFound) {
context.res = await onNotFound(context)
}
return Promise.resolve(context)
}
return Promise.resolve(handler(context, () => dispatch(i + 1)))
.then((res: Response) => {
// If handler return Response like `return c.text('foo')`
if (res && context instanceof HonoContext) {
context.res = res
}
return context
})
.catch((err) => {
if (context instanceof HonoContext && onError) {
if (err instanceof Error) {
context.res = onError(err, context)
}
return context
} else {
throw err
}
})
}
}
}