-
Notifications
You must be signed in to change notification settings - Fork 0
/
route.js
80 lines (68 loc) · 1.58 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
var pathToRegexp = require('path-to-regexp');
function decode_param(val){
if (typeof val !== 'string') {
return val;
}
try {
var result = decodeURIComponent(val);
if (result && result[result.length - 1] === '?') {
result = result.substr(0, result.length - 1);
}
return result;
} catch (e) {
console.log('Failed to decode value');
return val;
}
}
module.exports = function(routes) {
/**
* Get route from path
*
* @param path
*/
function getRoute(path, callback) {
var result = routes.filter(function(route) {
var params = [];
var re = pathToRegexp(route.in, params);
var m = re.exec(path);
return m !== undefined;
});
if (result && result.length > 0) {
return callback(null, result[0]);
}
return callback(new Error('No matching route found'));
}
function exists(path, callback) {
getRoute(path, function(err, route) {
if (err || !route) {
return callback(false);
}
return callback(true);
});
}
function getParams(path, route, callback) {
var params = [];
var re = pathToRegexp(route.in, params);
var m = re.exec(path);
var result = {};
var keys = re.keys;
var n = 0;
var key;
var val;
for (var i = 1, len = m.length; i < len; ++i) {
key = keys[i - 1];
val = decode_param(m[i]);
if (key) {
result[key.name] = val;
} else {
result[n++] = val;
}
}
return callback(null, result);
}
return {
exists: exists,
getParams: getParams,
getRoute: getRoute,
};
};