forked from typestack/routing-controllers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBaseDriver.ts
210 lines (173 loc) · 6.51 KB
/
BaseDriver.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
import { ValidatorOptions } from 'class-validator';
import { ClassTransformOptions, instanceToPlain } from 'class-transformer';
import { HttpError } from '../http-error/HttpError';
import { CurrentUserChecker } from '../CurrentUserChecker';
import { AuthorizationChecker } from '../AuthorizationChecker';
import { ActionMetadata } from '../metadata/ActionMetadata';
import { ParamMetadata } from '../metadata/ParamMetadata';
import { MiddlewareMetadata } from '../metadata/MiddlewareMetadata';
import { Action } from '../Action';
import { RoutingControllersOptions } from '../RoutingControllersOptions';
/**
* Base driver functionality for all other drivers.
* Abstract layer to organize controllers integration with different http server implementations.
*/
export abstract class BaseDriver {
// -------------------------------------------------------------------------
// Public Properties
// -------------------------------------------------------------------------
/**
* Reference to the underlying framework app object.
*/
app: any;
/**
* Indicates if class-transformer should be used or not.
*/
useClassTransformer: boolean;
/**
* Indicates if class-validator should be used or not.
*/
enableValidation: boolean;
/**
* Global class transformer options passed to class-transformer during classToPlain operation.
* This operation is being executed when server returns response to user.
*/
classToPlainTransformOptions: ClassTransformOptions;
/**
* Global class-validator options passed during validate operation.
*/
validationOptions: ValidatorOptions;
/**
* Global class transformer options passed to class-transformer during plainToClass operation.
* This operation is being executed when parsing user parameters.
*/
plainToClassTransformOptions: ClassTransformOptions;
/**
* Indicates if default routing-controllers error handler should be used or not.
*/
isDefaultErrorHandlingEnabled: boolean;
/**
* Indicates if routing-controllers should operate in development mode.
*/
developmentMode: boolean;
/**
* Global application prefix.
*/
routePrefix: string | RegExp = '';
/**
* Indicates if cors are enabled.
* This requires installation of additional module (cors for express and @koa/cors for koa).
*/
cors?: boolean | Object;
/**
* Map of error overrides.
*/
errorOverridingMap: { [key: string]: any };
/**
* Special function used to check user authorization roles per request.
* Must return true or promise with boolean true resolved for authorization to succeed.
*/
authorizationChecker?: AuthorizationChecker;
/**
* Special function used to get currently authorized user.
*/
currentUserChecker?: CurrentUserChecker;
// -------------------------------------------------------------------------
// Protected Methods
// -------------------------------------------------------------------------
protected transformResult(result: any, action: ActionMetadata, options: Action): any {
// check if we need to transform result
const shouldTransform =
this.useClassTransformer && // transform only if class-transformer is enabled
action.options.transformResponse !== false && // don't transform if action response transform is disabled
result instanceof Object && // don't transform primitive types (string/number/boolean)
!(
(result instanceof Uint8Array || result.pipe instanceof Function) // don't transform binary data // don't transform streams
);
// transform result if needed
if (shouldTransform) {
const options = action.responseClassTransformOptions || this.classToPlainTransformOptions;
result = instanceToPlain(result, options);
}
return result;
}
protected processJsonError(error: any) {
if (!this.isDefaultErrorHandlingEnabled) return error;
if (typeof error.toJSON === 'function') return error.toJSON();
let processedError: any = {};
if (error instanceof Error) {
const name = error.name && error.name !== 'Error' ? error.name : error.constructor.name;
processedError.name = name;
if (error.message) processedError.message = error.message;
if (error.stack && this.developmentMode) processedError.stack = error.stack;
Object.keys(error)
.filter(
key =>
key !== 'stack' &&
key !== 'name' &&
key !== 'message' &&
(!(error instanceof HttpError) || key !== 'httpCode')
)
.forEach(key => (processedError[key] = (error as any)[key]));
if (this.errorOverridingMap)
Object.keys(this.errorOverridingMap)
.filter(key => name === key)
.forEach(key => (processedError = this.merge(processedError, this.errorOverridingMap[key])));
return Object.keys(processedError).length > 0 ? processedError : undefined;
}
return error;
}
protected processTextError(error: any) {
if (!this.isDefaultErrorHandlingEnabled) return error;
if (error instanceof Error) {
if (this.developmentMode && error.stack) {
return error.stack;
} else if (error.message) {
return error.message;
}
}
return error;
}
protected merge(obj1: any, obj2: any): any {
const result: any = {};
for (const i in obj1) {
if (i in obj2 && typeof obj1[i] === 'object' && i !== null) {
result[i] = this.merge(obj1[i], obj2[i]);
} else {
result[i] = obj1[i];
}
}
for (const i in obj2) {
result[i] = obj2[i];
}
return result;
}
/**
* Initializes the things driver needs before routes and middleware registration.
*/
abstract initialize(): void;
/**
* Registers given middleware.
*/
abstract registerMiddleware(middleware: MiddlewareMetadata, options: RoutingControllersOptions): void;
/**
* Registers action in the driver.
*/
abstract registerAction(action: ActionMetadata, executeCallback: (options: Action) => any): void;
/**
* Registers all routes in the framework.
*/
abstract registerRoutes(): void;
/**
* Gets param from the request.
*/
abstract getParamFromRequest(actionOptions: Action, param: ParamMetadata): any;
/**
* Defines an algorithm of how to handle error during executing controller action.
*/
abstract handleError(error: any, action: ActionMetadata, options: Action): any;
/**
* Defines an algorithm of how to handle success result of executing controller action.
*/
abstract handleSuccess(result: any, action: ActionMetadata, options: Action): void;
}