-
Notifications
You must be signed in to change notification settings - Fork 7
/
controller.ts
92 lines (84 loc) · 2.09 KB
/
controller.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { IOptions } from 'glob'
import {
rollUpState,
findControllers,
HttpVerbs,
getStateAndTarget,
IStateAndTarget,
IAwilixControllerBuilder,
ClassOrFunctionReturning
} from 'awilix-router-core'
import { makeInvoker } from './invokers'
import { Router } from 'express'
/**
* Constructor type.
*/
export type ConstructorOrControllerBuilder =
| (new (...args: any[]) => any)
| IAwilixControllerBuilder
/**
* Registers one or multiple decorated controller classes.
*
* @param ControllerClass One or multiple "controller" classes
* with decorators to register
*/
export function controller(
ControllerClass:
| ConstructorOrControllerBuilder
| ConstructorOrControllerBuilder[]
): Router {
const router = Router()
if (Array.isArray(ControllerClass)) {
ControllerClass.forEach(c =>
_registerController(router, getStateAndTarget(c))
)
} else {
_registerController(router, getStateAndTarget(ControllerClass))
}
return router
}
/**
* Loads controllers for the given pattern.
*
* @param pattern
* @param opts
*/
export function loadControllers(pattern: string, opts?: IOptions): Router {
const router = Router()
findControllers(pattern, {
...opts,
absolute: true
}).forEach(_registerController.bind(null, router))
return router
}
/**
* Reads the config state and registers the routes in the router.
*
* @param router
* @param ControllerClass
*/
function _registerController(
router: Router,
stateAndTarget: IStateAndTarget | null
): void {
if (!stateAndTarget) {
return
}
const { state, target } = stateAndTarget
const rolledUp = rollUpState(state)
rolledUp.forEach((methodCfg, methodName) => {
methodCfg.verbs.forEach(httpVerb => {
let method = httpVerb.toLowerCase()
if (httpVerb === HttpVerbs.ALL) {
method = 'all'
}
;(router as any)[method](
methodCfg.paths,
...methodCfg.beforeMiddleware,
/*tslint:disable-next-line*/
makeInvoker(target as ClassOrFunctionReturning<any>)(methodName as any),
...methodCfg.afterMiddleware
)
})
})
}