-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
112 lines (92 loc) · 1.84 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
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
/**
* Module dependencies.
*/
var toRegexp = require('path-to-regexp');
/**
* Expose `Route`.
*/
module.exports = Route;
/**
* Initialize a route with the given `path`.
*
* @param {String|Regexp} path
* @return {Type}
* @api public
*/
function Route(path) {
this.path = path;
this.keys = [];
this.regexp = toRegexp(path, this.keys);
this._before = [];
this._after = [];
}
/**
* Add before `fn`.
*
* @param {Function} fn
* @return {Route} self
* @api public
*/
Route.prototype.before = function(fn){
this._before.push(fn);
return this;
};
/**
* Add after `fn`.
*
* @param {Function} fn
* @return {Route} self
* @api public
*/
Route.prototype.after = function(fn){
this._after.push(fn);
return this;
};
/**
* Invoke callbacks for `type` with `args`.
*
* @param {String} type
* @param {Array} args
* @api public
*/
Route.prototype.call = function(type, args){
args = args || [];
var fns = this['_' + type];
if (!fns) throw new Error('invalid type');
for (var i = 0; i < fns.length; i++) {
fns[i].apply(null, args);
}
};
/**
* 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' == typeof 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;
};