-
-
Notifications
You must be signed in to change notification settings - Fork 445
/
compose.ts
76 lines (70 loc) · 2.13 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { HonoContext } from './context.ts'
import type { Environment, NotFoundHandler, ErrorHandler } from './hono.ts'
interface ComposeContext {
finalized: boolean
res: any
}
// Based on the code in the MIT licensed `koa-compose` package.
export const compose = <C extends ComposeContext, E extends Partial<Environment> = Environment>(
middleware: Function[],
onNotFound?: NotFoundHandler<E>,
onError?: ErrorHandler<E>
) => {
const middlewareLength = middleware.length
return (context: C, next?: Function) => {
let index = -1
return dispatch(0)
function dispatch(i: number): C | Promise<C> {
if (i <= index) {
throw new Error('next() called multiple times')
}
let handler = middleware[i]
index = i
if (i === middlewareLength && next) handler = next
let res
let isError = false
if (!handler) {
if (context instanceof HonoContext && context.finalized === false && onNotFound) {
res = onNotFound(context)
}
} 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
}
}
}
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
})
}
}
}
}