/
express.ts
174 lines (148 loc) · 4.64 KB
/
express.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import { RequestHandler, Application, Router, Express, Request, Response, NextFunction } from 'express';
import { Container } from '@decorators/di';
import { ExpressMeta, getMeta, ParameterType, ExpressClass, Route, ParameterConfiguration } from './meta';
import { middlewareHandler, errorMiddlewareHandler, Type } from './middleware';
/**
* Attach controllers to express application
*
* @param {Express} app Express application
* @param {Type[]} controllers Controllers array
*/
export function attachControllers(app: Express | Router, controllers: Type[]) {
controllers.forEach((controller: Type) => registerController(app, controller, getController));
// error middleware must be registered as the very last one
app.use(errorMiddlewareHandler());
}
/**
* Attach controller instances to express application
*
* @param {Express} app Express application
* @param {any[]} controllers Controllers array
*/
export function attachControllerInstances(app: Express | Router, controllers: object[]) {
controllers.forEach((controller: Type) => registerController(app, controller, (c: object) => c ));
// error middleware must be registered as the very last one
app.use(errorMiddlewareHandler());
}
/**
* Register controller via registering new Router
*
* @param {Application} app
* @param {ExpressClass} Controller
* @returns
*/
function registerController(app: Application | Router, Controller: Type|object, getController: (c: Type|object) => ExpressClass) {
const controller: ExpressClass = getController(Controller);
const meta: ExpressMeta = getMeta(controller);
const router: Router = Router();
const routes: object = meta.routes;
const url: string = meta.url;
const params: object = meta.params;
/**
* Wrap all registered middleware with helper function
* that can instantiate or get from the container instance of the class
* or execute given middleware function
* @see getMiddleware
*/
const routerMiddleware: RequestHandler[] = (meta.middleware || [])
.map(middleware => middlewareHandler(middleware));
/**
* Apply router middleware
*/
if (routerMiddleware.length) {
router.use(...routerMiddleware);
}
/**
* Applying registered routes
*/
for (const methodName of Object.keys(routes)) {
const route: Route = routes[methodName];
const routeHandler = (req, res, next) => {
const args = extractParameters(req, res, next, params[methodName]);
const handler = controller[methodName].apply(controller, args);
if (handler instanceof Promise) {
handler.catch(next);
}
return handler;
};
const routeMiddleware: RequestHandler[] = (route.middleware || [])
.map(middleware => middlewareHandler(middleware));
router[route.method].apply(router, [
route.url, ...routeMiddleware, routeHandler
]);
}
app.use(url, router);
return app;
}
/**
* Extract parameters for handlers
*
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @param {ParameterConfiguration[]} params
*
* @returns {any[]}
*/
function extractParameters(req: Request, res: Response, next: NextFunction, params: ParameterConfiguration[]): any[] {
if (!params || !params.length) {
return [ req, res, next ];
}
const args = [];
for (const { name, index, type } of params) {
switch (type) {
case ParameterType.RESPONSE:
args[index] = res;
break;
case ParameterType.REQUEST:
args[index] = getParam(req, null, name);
break;
case ParameterType.NEXT:
args[index] = next;
break;
case ParameterType.PARAMS:
args[index] = getParam(req, 'params', name);
break;
case ParameterType.QUERY:
args[index] = getParam(req, 'query', name);
break;
case ParameterType.BODY:
args[index] = getParam(req, 'body', name);
break;
case ParameterType.HEADERS:
args[index] = getParam(req, 'headers', name);
break;
case ParameterType.COOKIES:
args[index] = getParam(req, 'cookies', name);
break;
}
}
return args;
}
/**
* Get controller instance from container or instantiate one
*
* @param {any} Controller
*
* @returns {ExpressClass}
*/
function getController(Controller: Type): ExpressClass {
try {
return Container.get(Controller);
} catch {
return new Controller();
}
}
/**
* Get parameter value from the source object
*
* @param {*} source
* @param {string} paramType
* @param {string} name
*
* @returns {*}
*/
function getParam(source: any, paramType: string, name: string): any {
const param = source[paramType] || source;
return name ? param[name] : param;
}