-
Notifications
You must be signed in to change notification settings - Fork 405
/
Copy pathExpressDriver.ts
468 lines (413 loc) · 15.7 KB
/
ExpressDriver.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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
import { UseMetadata } from '../../metadata/UseMetadata';
import { MiddlewareMetadata } from '../../metadata/MiddlewareMetadata';
import { ActionMetadata } from '../../metadata/ActionMetadata';
import { Action } from '../../Action';
import { ParamMetadata } from '../../metadata/ParamMetadata';
import { BaseDriver } from '../BaseDriver';
import { ExpressMiddlewareInterface } from './ExpressMiddlewareInterface';
import { ExpressErrorMiddlewareInterface } from './ExpressErrorMiddlewareInterface';
import { AccessDeniedError } from '../../error/AccessDeniedError';
import { AuthorizationCheckerNotDefinedError } from '../../error/AuthorizationCheckerNotDefinedError';
import { isPromiseLike } from '../../util/isPromiseLike';
import { getFromContainer } from '../../container';
import { AuthorizationRequiredError } from '../../error/AuthorizationRequiredError';
import { NotFoundError, RoutingControllersOptions } from '../../index';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const cookie = require('cookie');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const templateUrl = require('template-url');
/**
* Integration with express framework.
*/
export class ExpressDriver extends BaseDriver {
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(public express?: any) {
super();
this.loadExpress();
this.app = this.express;
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Initializes the things driver needs before routes and middlewares registration.
*/
initialize() {
if (this.cors) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const cors = require('cors');
if (this.cors === true) {
this.express.use(cors());
} else {
this.express.use(cors(this.cors));
}
}
}
/**
* Registers middleware that run before controller actions.
*/
registerMiddleware(middleware: MiddlewareMetadata, options: RoutingControllersOptions): void {
let middlewareWrapper;
// if its an error handler then register it with proper signature in express
if ((middleware.instance as ExpressErrorMiddlewareInterface).error) {
middlewareWrapper = (error: any, request: any, response: any, next: (err?: any) => any) => {
(middleware.instance as ExpressErrorMiddlewareInterface).error(error, request, response, next);
};
}
// if its a regular middleware then register it as express middleware
else if ((middleware.instance as ExpressMiddlewareInterface).use) {
middlewareWrapper = (request: any, response: any, next: (err: any) => any) => {
try {
const useResult = (middleware.instance as ExpressMiddlewareInterface).use(request, response, next);
if (isPromiseLike(useResult)) {
useResult.catch((error: any) => {
this.handleError(error, undefined, { request, response, next });
return error;
});
}
} catch (error) {
this.handleError(error, undefined, { request, response, next });
}
};
}
if (middlewareWrapper) {
// Name the function for better debugging
Object.defineProperty(middlewareWrapper, 'name', {
value: middleware.instance.constructor.name,
writable: true,
});
this.express.use(options.routePrefix || '/', middlewareWrapper);
}
}
/**
* Registers action in the driver.
*/
registerAction(actionMetadata: ActionMetadata, executeCallback: (options: Action) => any): void {
// middlewares required for this action
const defaultMiddlewares: any[] = [];
if (actionMetadata.isBodyUsed) {
if (actionMetadata.isJsonTyped) {
defaultMiddlewares.push(this.loadBodyParser().json(actionMetadata.bodyExtraOptions));
} else {
defaultMiddlewares.push(this.loadBodyParser().text(actionMetadata.bodyExtraOptions));
}
}
if (actionMetadata.isAuthorizedUsed) {
defaultMiddlewares.push((request: any, response: any, next: Function) => {
if (!this.authorizationChecker) throw new AuthorizationCheckerNotDefinedError();
const action: Action = { request, response, next };
try {
const checkResult = this.authorizationChecker(action, actionMetadata.authorizedRoles);
const handleError = (result: any) => {
if (!result) {
const error =
actionMetadata.authorizedRoles.length === 0
? new AuthorizationRequiredError(action)
: new AccessDeniedError(action);
this.handleError(error, actionMetadata, action);
} else {
next();
}
};
if (isPromiseLike(checkResult)) {
checkResult
.then(result => handleError(result))
.catch(error => this.handleError(error, actionMetadata, action));
} else {
handleError(checkResult);
}
} catch (error) {
this.handleError(error, actionMetadata, action);
}
});
}
if (actionMetadata.isFileUsed || actionMetadata.isFilesUsed) {
const multer = this.loadMulter();
actionMetadata.params
.filter(param => param.type === 'file')
.forEach(param => {
defaultMiddlewares.push(multer(param.extraOptions).single(param.name));
});
actionMetadata.params
.filter(param => param.type === 'files')
.forEach(param => {
defaultMiddlewares.push(multer(param.extraOptions).array(param.name));
});
}
// user used middlewares
const uses = [...actionMetadata.controllerMetadata.uses, ...actionMetadata.uses];
const beforeMiddlewares = this.prepareMiddlewares(uses.filter(use => !use.afterAction));
const afterMiddlewares = this.prepareMiddlewares(uses.filter(use => use.afterAction));
// prepare route and route handler function
const route = ActionMetadata.appendBaseRoute(this.routePrefix, actionMetadata.fullRoute);
const routeHandler = function routeHandler(request: any, response: any, next: Function) {
return executeCallback({ request, response, next });
};
// This ensures that a request is only processed once to prevent unhandled rejections saying
// "Can't set headers after they are sent"
// Some examples of reasons a request may cause multiple route calls:
// * Express calls the "get" route automatically when we call the "head" route:
// Reference: https://expressjs.com/en/4x/api.html#router.METHOD
// This causes a double execution on our side.
// * Multiple routes match the request (e.g. GET /users/me matches both @All(/users/me) and @Get(/users/:id)).
// The following middleware only starts an action processing if the request has not been processed before.
const routeGuard = function routeGuard(request: any, response: any, next: Function) {
if (!request.routingControllersStarted) {
request.routingControllersStarted = true;
return next();
}
};
// finally register action in express
this.express[actionMetadata.type.toLowerCase()](
...[route, routeGuard, ...beforeMiddlewares, ...defaultMiddlewares, routeHandler, ...afterMiddlewares]
);
}
/**
* Registers all routes in the framework.
*/
// eslint-disable-next-line @typescript-eslint/no-empty-function
registerRoutes() {}
/**
* Gets param from the request.
*/
getParamFromRequest(action: Action, param: ParamMetadata): any {
const request: any = action.request;
switch (param.type) {
case 'body':
return request.body;
case 'body-param':
return request.body[param.name];
case 'param':
return request.params[param.name];
case 'params':
return request.params;
case 'session-param':
return request.session[param.name];
case 'session':
return request.session;
case 'state':
throw new Error('@State decorators are not supported by express driver.');
case 'query':
return request.query[param.name];
case 'queries':
return request.query;
case 'header':
return request.headers[param.name.toLowerCase()];
case 'headers':
return request.headers;
case 'file':
return request.file;
case 'files':
return request.files;
case 'cookie':
if (!request.headers.cookie) return;
const cookies = cookie.parse(request.headers.cookie);
return cookies[param.name];
case 'cookies':
if (!request.headers.cookie) return {};
return cookie.parse(request.headers.cookie);
}
}
/**
* Handles result of successfully executed controller action.
*/
handleSuccess(result: any, action: ActionMetadata, options: Action): void {
// if the action returned the response object itself, short-circuits
if (result && result === options.response) {
options.next();
return;
}
// transform result if needed
result = this.transformResult(result, action, options);
// set http status code
if (result === undefined && action.undefinedResultCode) {
if (action.undefinedResultCode instanceof Function) {
throw new (action.undefinedResultCode as any)(options);
}
options.response.status(action.undefinedResultCode);
} else if (result === null) {
if (action.nullResultCode) {
if (action.nullResultCode instanceof Function) {
throw new (action.nullResultCode as any)(options);
}
options.response.status(action.nullResultCode);
} else {
options.response.status(204);
}
} else if (action.successHttpCode) {
options.response.status(action.successHttpCode);
}
// apply http headers
Object.keys(action.headers).forEach(name => {
options.response.header(name, action.headers[name]);
});
if (action.redirect) {
// if redirect is set then do it
if (typeof result === 'string') {
options.response.redirect(result);
} else if (result instanceof Object) {
options.response.redirect(templateUrl(action.redirect, result));
} else {
options.response.redirect(action.redirect);
}
options.next();
} else if (action.renderedTemplate) {
// if template is set then render it
const renderOptions = result && result instanceof Object ? result : {};
options.response.render(action.renderedTemplate, renderOptions, (err: any, html: string) => {
if (err && action.isJsonTyped) {
return options.next(err);
} else if (err && !action.isJsonTyped) {
return options.next(err);
} else if (html) {
options.response.send(html);
}
options.next();
});
} else if (result === undefined) {
// throw NotFoundError on undefined response
if (action.undefinedResultCode) {
if (action.isJsonTyped) {
options.response.json();
} else {
options.response.send();
}
options.next();
} else {
throw new NotFoundError();
}
} else if (result === null) {
// send null response
if (action.isJsonTyped) {
options.response.json(null);
} else {
options.response.send(null);
}
options.next();
} else if (result instanceof Buffer) {
// check if it's binary data (Buffer)
options.response.end(result, 'binary');
} else if (result instanceof Uint8Array) {
// check if it's binary data (typed array)
options.response.end(Buffer.from(result as any), 'binary');
} else if (result.pipe instanceof Function) {
result.pipe(options.response);
} else {
// send regular result
if (action.isJsonTyped) {
options.response.json(result);
} else {
options.response.send(result);
}
options.next();
}
}
/**
* Handles result of failed executed controller action.
*/
handleError(error: any, action: ActionMetadata | undefined, options: Action): any {
if (this.isDefaultErrorHandlingEnabled) {
const response: any = options.response;
// set http code
// note that we can't use error instanceof HttpError properly anymore because of new typescript emit process
if (error.httpCode) {
response.status(error.httpCode);
} else {
response.status(500);
}
// apply http headers
if (action) {
Object.keys(action.headers).forEach(name => {
response.header(name, action.headers[name]);
});
}
// send error content
if (action && action.isJsonTyped) {
response.json(this.processJsonError(error));
} else {
response.send(this.processTextError(error)); // todo: no need to do it because express by default does it
}
}
options.next(error);
}
// -------------------------------------------------------------------------
// Protected Methods
// -------------------------------------------------------------------------
/**
* Creates middlewares from the given "use"-s.
*/
protected prepareMiddlewares(uses: UseMetadata[]) {
const middlewareFunctions: Function[] = [];
uses.forEach((use: UseMetadata) => {
if (use.middleware.prototype && use.middleware.prototype.use) {
// if this is function instance of MiddlewareInterface
middlewareFunctions.push((request: any, response: any, next: (err: any) => any) => {
try {
const useResult = getFromContainer<ExpressMiddlewareInterface>(use.middleware).use(request, response, next);
if (isPromiseLike(useResult)) {
useResult.catch((error: any) => {
this.handleError(error, undefined, { request, response, next });
return error;
});
}
return useResult;
} catch (error) {
this.handleError(error, undefined, { request, response, next });
}
});
} else if (use.middleware.prototype && use.middleware.prototype.error) {
// if this is function instance of ErrorMiddlewareInterface
middlewareFunctions.push(function (error: any, request: any, response: any, next: (err: any) => any) {
return getFromContainer<ExpressErrorMiddlewareInterface>(use.middleware).error(
error,
request,
response,
next
);
});
} else {
middlewareFunctions.push(use.middleware);
}
});
return middlewareFunctions;
}
/**
* Dynamically loads express module.
*/
protected loadExpress() {
if (require) {
if (!this.express) {
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
this.express = require('express')();
} catch (e) {
throw new Error('express package was not found installed. Try to install it: npm install express --save');
}
}
} else {
throw new Error('Cannot load express. Try to install all required dependencies.');
}
}
/**
* Dynamically loads body-parser module.
*/
protected loadBodyParser() {
try {
return require('body-parser');
} catch (e) {
throw new Error('body-parser package was not found installed. Try to install it: npm install body-parser --save');
}
}
/**
* Dynamically loads multer module.
*/
protected loadMulter() {
try {
return require('multer');
} catch (e) {
throw new Error('multer package was not found installed. Try to install it: npm install multer --save');
}
}
}