-
-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathcompose.ts
More file actions
73 lines (66 loc) · 2.15 KB
/
compose.ts
File metadata and controls
73 lines (66 loc) · 2.15 KB
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
import type { Context } from './context'
import type { Env, ErrorHandler, Next, NotFoundHandler } from './types'
/**
* Compose middleware functions into a single function based on `koa-compose` package.
*
* @template E - The environment type.
*
* @param {[[Function, unknown], unknown][] | [[Function]][]} middleware - An array of middleware functions and their corresponding parameters.
* @param {ErrorHandler<E>} [onError] - An optional error handler function.
* @param {NotFoundHandler<E>} [onNotFound] - An optional not-found handler function.
*
* @returns {(context: Context, next?: Next) => Promise<Context>} - A composed middleware function.
*/
export const compose = <E extends Env = Env>(
middleware: [[Function, unknown], unknown][] | [[Function]][],
onError?: ErrorHandler<E>,
onNotFound?: NotFoundHandler<E>
): ((context: Context, next?: Next) => Promise<Context>) => {
return (context, next) => {
let index = -1
return dispatch(0)
/**
* Dispatch the middleware functions.
*
* @param {number} i - The current index in the middleware array.
*
* @returns {Promise<Context>} - A promise that resolves to the context.
*/
async function dispatch(i: number): Promise<Context> {
if (i <= index) {
throw new Error('next() called multiple times')
}
index = i
let res
let isError = false
let handler
if (middleware[i]) {
handler = middleware[i][0][0]
context.req.routeIndex = i
} else {
handler = (i === middleware.length && next) || undefined
}
if (handler) {
try {
res = await handler(context, () => dispatch(i + 1))
} catch (err) {
if (err instanceof Error && onError) {
context.error = err
res = await onError(err, context)
isError = true
} else {
throw err
}
}
} else {
if (context.finalized === false && onNotFound) {
res = await onNotFound(context)
}
}
if (res && (context.finalized === false || isError)) {
context.res = res
}
return context
}
}
}