forked from component/route
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
80 lines (67 loc) · 1.58 KB
/
index.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
/**
* Import(s)
*/
var toRegexp = require('path-to-regexp');
var type = (typeof window !== 'undefined' && window !== null)
? require('type') : require('type-component');
/**
* Export(s)
*/
module.exports = Route;
/**
* Initialize a route with the given `path`,
* and an array of `callbacks` and `options`.
*
* Options:
*
* - `sensitive` enable case-sensitive routes
* - `strict` enable strict matching for trailing slashes
*
* @param {String|Regexp} path
* @param {Array} callbacks
* @param {Object} options.
* @api public
*/
function Route(path, callbacks, options) {
if (type(callbacks) === 'object') {
options = callbacks;
callbacks = undefined;
}
this.path = path;
this.keys = [];
this.callbacks = callbacks;
this.regexp = toRegexp(path, this.keys, options);
}
/**
* Check if `path` matches this route,
* returning `false` or an object.
*
* @param {String} path
* @return {Object}
* @api public
*/
Route.prototype.match = function (path) {
var keys = this.keys;
var qsIndex = path.indexOf('?');
var pathname = ~qsIndex ? path.slice(0, qsIndex) : path;
var m = this.regexp.exec(pathname);
var params = [];
var args = [];
if (!m) return false;
for (var i = 1, len = m.length; i < len; ++i) {
var key = keys[i - 1];
var val = 'string' == type(m[i])
? decodeURIComponent(m[i])
: m[i];
if (key) {
params[key.name] = undefined !== params[key.name]
? params[key.name]
: val;
} else {
params.push(val);
}
args.push(val);
}
params.args = args;
return params;
};