-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
middleware.ts
52 lines (42 loc) · 1.17 KB
/
middleware.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
import { AppMiddleware, MiddlewareArgument, Router } from "./types.ts"
export function middleware() {
const middlewares: AppMiddleware[] = []
function isRegex(regexPath: MiddlewareArgument) {
return regexPath instanceof RegExp
}
function isString(path: MiddlewareArgument) {
return typeof path === "string"
}
function isRouter(element: Router) {
return element.routes !== undefined
}
function isContainRouter(array: MiddlewareArgument[]) {
for (let index = 0; index < array.length; index++) {
const element = array[index]
const yes = isRouter(<Router>element)
if (yes) return true
}
return false
}
function useMiddleware(...array: MiddlewareArgument[]) {
const [first, ...rest] = array
let path: RegExp | string = "/.*"
let appMiddlewares = rest
let type = ""
if (isRegex(first)) {
path = <RegExp>first
} else if (isString(first)) {
path = <string>first
} else {
appMiddlewares = array
}
if (isContainRouter(rest)) {
type = "router"
}
middlewares.push({ path, middlewares: appMiddlewares, type })
}
return {
useMiddleware,
middlewares,
}
}