-
-
Notifications
You must be signed in to change notification settings - Fork 444
/
compose.ts
54 lines (48 loc) · 1.45 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
49
50
51
52
53
54
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
) => {
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
}
let res!: Response
let isError: boolean = false
try {
const tmp = handler(context, () => dispatch(i + 1))
res = tmp instanceof Promise ? await tmp : tmp
} catch (err) {
if (context instanceof HonoContext && onError) {
if (err instanceof Error) {
isError = true
res = onError(err, context)
}
}
if (!res) {
throw err
}
}
if (res && context instanceof HonoContext && (!context.finalized || isError)) {
context.res = res
}
return context
}
}
}