/
route.js
259 lines (208 loc) · 7.56 KB
/
route.js
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
define(function(require, exports, module) {
"use strict";
var Params = require("./params");
var flatten = require("./utils").flatten;
var error = require("http-error");
function prepareParams( options, types, parent ){
var params = Params.normalize(options.params, types );
if ( parent ){
for ( var key in parent.params ){
if ( params[key] ) continue;
params[key] = parent.params[key];
}
}
return params;
}
module.exports = function Route(route, options, handler, types, parent ) {
// options is optional
if (typeof options == "function" || Array.isArray(options)) {
types = handler;
handler = options;
options = {};
}
options.route = route;
this.middlewares = flatten(handler);
this.middlewares = this.middlewares.map(function(handler) {
if (handler.length == 2) {
handler = wrapHandler(handler);
}
return handler;
});
this.middlewares.unshift(decodeParams);
this.method = (options.method || "GET").toLowerCase();
var self = this;
var keys = [];
var params = prepareParams( options, types, parent );
var routeRe = normalizePath(options.route, keys, params);
function wrapHandler(handler) {
return function(req, res, next) {
handler(req.params || {}, function(err, json, headers, code) {
if (err) return next(err);
res.json(json, headers, code);
});
};
}
/**
* Creates a rgular expression to match this route.
* Url param names are stored in `keys` and the `params` are completed with
* the default values for url parameters.
*/
function normalizePath(path, keys, params) {
path = path
.concat("/?")
.replace(/\/:([\w\.\-\_]+)(\*?)/g, function(match, key, wildcard) {
keys.push(key);
if (!params[key]) {
params[key] = Params.param( key );
}
// url params default to type string and optional=false
var param = params[key];
if (param.source !== "url")
throw new Error("Url parameters must have 'url' as source but found '" + param.source + "'");
if (wildcard)
return "(/*)";
else
return "/([^\\/]+)";
})
.replace(/([\/.])/g, '\\$1')
.replace(/\*/g, '(.*)');
return new RegExp('^' + path + '$');
}
/**
* Check if the given path matched the route regular expression. If
* the regular expression doesn't match or parsing fails `match` will
* return `false`
**/
this.match = function(req, path) {
var m = path.match(routeRe);
if (!m) return false;
var match = {};
for (var i = 0; i < keys.length; i++) {
var value = m[i+1];
var key = keys[i];
var param = params[key];
var type = param.type;
try {
value = type.parse(value);
} catch (e) {
return false;
}
if (!type.check(value)) {
return false;
}
match[key] = value;
}
req.match = match;
return true;
};
/**
* Middleware to validate the parameters. It will take `req.match` for
* url params, decode the query and body parameters. If validation passes
* the decoded and validated parameters are stored in `req.params`
* otherwhise an error is returned.
*/
function decodeParams(req, res, next) {
var urlParams = req.match;
if (!urlParams) return;
var body = req.body || {};
var query = req.parsedUrl.query;
req.params = req.params || {};
var errors = [];
// marker object
var EMPTY = {};
// 1. check if all required params are there
for (var key in params) {
var param = params[key];
if( keys.indexOf(key) == -1 ) continue;
if (
(!param.optional) && (
(param.source == "body" && !(key in body)) ||
(param.source == "query" && !(key in query)) ||
(param.source == "url" && !(key in urlParams))
)
) {
errors.push({
"resource": self.name || "root",
"field": key,
"source": param.source,
"code": "missing_field"
});
}
else {
var type = param.type;
var value = EMPTY;
var isValid = true;
switch(param.source) {
case "body":
if (param.optional && !(key in body))
break;
value = body[key]; // body is already JSON parsed
isValid = type.check(value);
break;
case "query":
if (param.optional && !(key in query))
break;
try {
value = type.parse(query[key]);
} catch(e) {
isValid = false;
}
isValid = isValid === false ? false : type.check(value);
break;
case "url":
if (param.optional && !(key in urlParams))
break;
value = urlParams[key]; // is already parsed and checked
isValid = true;
break;
}
if (!isValid) {
errors.push({
"resource": self.name || "root",
"field": key,
"type_expected": type.toString(),
"code": "invalid"
});
}
else {
if (value !== EMPTY)
req.params[key] = value;
else if ("default" in param)
req.params[key] = param.default;
}
}
}
if (errors.length) {
var err = new error.UnprocessableEntity("Validation failed");
err.errors = errors;
return next(err);
}
next();
}
this.describe = function() {
var route = {
route: options.route,
method: this.method
};
if (options.name)
route.name = options.name;
if (options.description)
route.description = options.description;
route.params = {};
for (var name in params) {
var param = params[name];
route.params[name] = {
name: param.name,
type: param.type.toString(),
source: param.source,
optional: param.optional
};
if (param.description)
route.params[name].description = param.description;
}
if (!Object.keys(route.params).length)
delete route.params;
return route;
};
};
});