-
Notifications
You must be signed in to change notification settings - Fork 391
/
ActionParameterHandler.ts
201 lines (161 loc) · 7.43 KB
/
ActionParameterHandler.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
import {plainToClass} from "class-transformer";
import {validateOrReject as validate, ValidationError} from "class-validator";
import {Action} from "./Action";
import {BadRequestError} from "./http-error/BadRequestError";
import {BaseDriver} from "./driver/BaseDriver";
import {ParameterParseJsonError} from "./error/ParameterParseJsonError";
import {ParamMetadata} from "./metadata/ParamMetadata";
import {ParamRequiredError} from "./error/ParamRequiredError";
import {AuthorizationRequiredError} from "./error/AuthorizationRequiredError";
import {CurrentUserCheckerNotDefinedError} from "./error/CurrentUserCheckerNotDefinedError";
import {isPromiseLike} from "./util/isPromiseLike";
/**
* Handles action parameter.
*/
export class ActionParameterHandler<T extends BaseDriver> {
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(private driver: T) {
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Handles action parameter.
*/
handle(action: Action, param: ParamMetadata): Promise<any>|any {
if (param.type === "request")
return action.request;
if (param.type === "response")
return action.response;
if (param.type === "context")
return action.context;
// get parameter value from request and normalize it
const value = this.normalizeParamValue(this.driver.getParamFromRequest(action, param), param);
if (isPromiseLike(value))
return value.then(value => this.handleValue(value, action, param));
return this.handleValue(value, action, param);
}
// -------------------------------------------------------------------------
// Protected Methods
// -------------------------------------------------------------------------
/**
* Handles non-promise value.
*/
protected handleValue(value: any, action: Action, param: ParamMetadata): Promise<any>|any {
// if transform function is given for this param then apply it
if (param.transform)
value = param.transform(action, value);
// if its current-user decorator then get its value
if (param.type === "current-user") {
if (!this.driver.currentUserChecker)
throw new CurrentUserCheckerNotDefinedError();
value = this.driver.currentUserChecker(action);
}
// check cases when parameter is required but its empty and throw errors in this case
if (param.required) {
const isValueEmpty = value === null || value === undefined || value === "";
const isValueEmptyObject = value instanceof Object && Object.keys(value).length === 0;
if (param.type === "body" && !param.name && (isValueEmpty || isValueEmptyObject)) { // body has a special check and error message
return Promise.reject(new ParamRequiredError(action, param));
} else if (param.type === "current-user") { // current user has a special check as well
if (isPromiseLike(value)) {
return value.then(currentUser => {
if (!currentUser)
return Promise.reject(new AuthorizationRequiredError(action));
return currentUser;
});
} else {
if (!value)
return Promise.reject(new AuthorizationRequiredError(action));
}
} else if (param.name && isValueEmpty) { // regular check for all other parameters // todo: figure out something with param.name usage and multiple things params (query params, upload files etc.)
return Promise.reject(new ParamRequiredError(action, param));
}
}
return value;
}
/**
* Normalizes parameter value.
*/
protected normalizeParamValue(value: any, param: ParamMetadata): Promise<any>|any {
if (value === null || value === undefined)
return value;
switch (param.targetName) {
case "number":
if (value === "") return undefined;
return +value;
case "string":
return value;
case "boolean":
if (value === "true" || value === "1") {
return true;
} else if (value === "false" || value === "0") {
return false;
}
return !!value;
case "date":
const parsedDate = new Date(value);
if (isNaN(parsedDate.getTime())) {
return Promise.reject(new BadRequestError(`${param.name} is invalid! It can't be parsed to date.`));
}
return parsedDate;
default:
if (value && (param.parse || param.isTargetObject)) {
value = this.parseValue(value, param);
value = this.transformValue(value, param);
value = this.validateValue(value, param); // note this one can return promise
}
}
return value;
}
/**
* Parses string value into a JSON object.
*/
protected parseValue(value: any, paramMetadata: ParamMetadata): any {
if (typeof value === "string") {
try {
return JSON.parse(value);
} catch (error) {
throw new ParameterParseJsonError(paramMetadata.name, value);
}
}
return value;
}
/**
* Perform class-transformation if enabled.
*/
protected transformValue(value: any, paramMetadata: ParamMetadata): any {
if (this.driver.useClassTransformer &&
paramMetadata.targetType &&
paramMetadata.targetType !== Object &&
!(value instanceof paramMetadata.targetType)) {
const options = paramMetadata.classTransform || this.driver.plainToClassTransformOptions;
value = plainToClass(paramMetadata.targetType, value, options);
}
return value;
}
/**
* Perform class-validation if enabled.
*/
protected validateValue(value: any, paramMetadata: ParamMetadata): Promise<any>|any {
const isValidationEnabled = (paramMetadata.validate instanceof Object || paramMetadata.validate === true)
|| (this.driver.enableValidation === true && paramMetadata.validate !== false);
const shouldValidate = paramMetadata.targetType
&& (paramMetadata.targetType !== Object)
&& (value instanceof paramMetadata.targetType);
if (isValidationEnabled && shouldValidate) {
const options = paramMetadata.validate instanceof Object ? paramMetadata.validate : this.driver.validationOptions;
return validate(value, options)
.then(() => value)
.catch((validationErrors: ValidationError[]) => {
const error: any = new BadRequestError(`Invalid ${paramMetadata.type}, check 'errors' property for more info.`);
error.errors = validationErrors;
error.paramName = paramMetadata.name;
throw error;
});
}
return value;
}
}