-
Notifications
You must be signed in to change notification settings - Fork 31
/
router.js
266 lines (240 loc) · 8.31 KB
/
router.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
260
261
262
263
264
265
266
/**
* Copyright 2014, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
'use strict';
/*global process:true */
var debug = require('debug')('Routr:router');
var pathToRegexp = require('path-to-regexp');
var queryString = require('query-string');
var METHODS = {
GET: 'get'
};
var cachedCompilers = {};
/**
* @class Route
* @param {String} name The name of the route
* @param {Object} config The configuration for this route.
* @param {String} config.path The path of the route.
* @constructor
*/
function Route(name, config) {
this.name = name;
this.config = config || {};
this.keys = [];
this.regexp = pathToRegexp(this.config.path, this.keys);
}
/**
* Whether the given method is accepted by this route.
* @method acceptMethod
* @param {String} method The HTTP VERB string.
* @return true if the method is accepted; false otherwise.
* @for Route
*/
Route.prototype.acceptMethod = function (method) {
//TODO support array for method, ['get', 'post']
return (method && method.toLowerCase()) === (this.config.method && this.config.method.toLowerCase());
};
/**
* Checkes whether this route matches the given url, method (GET as default) and optional navigation related criteria.
* @method match
* @param {String} url The relative url to be matched to this route. Query strings and hash fragments
* are **not** considered when performing the match. E.g. /some_path?foo=bar#hashBaz
* would match to the same route as /some_path
* @param {Object} [options]
* @param {String} [options.method=get] The case-insensitive HTTP method string. Defaults to 'get'.
* @return {Object|null} The matched route params if path/method/navParams matches to this route; null otherwise.
* @for Route
*/
Route.prototype.match = function (url, options) {
if (!url) {
return null;
}
options = options || {};
var self = this;
var i;
var len;
// 1. check method
var method = options.method || METHODS.GET;
if (!self.acceptMethod(method)) {
return null;
}
// 2. check path
// remove query string and hash fragment from url
var pos = url.indexOf('?');
var path;
if (pos >= 0) {
// remove query string
path = url.substring(0, pos);
} else {
pos = url.indexOf('#');
if (pos >= 0) {
// hash fragment does not get sent to server.
// But since routr can be used on both server and client,
// we should remove hash fragment before matching the regex.
path = url.substring(0, pos);
} else {
path = url;
}
}
var pathMatches = self.regexp.exec(path);
if (!pathMatches) {
return null;
}
// 3. method/path/navParams all matched, extract the matched path params
var routeParams = {};
for (i = 0, len = self.keys.length; i < len; i++) {
// Don't overwrite a previously populated parameter with `undefined`.
// A route may legitimately have multiple instances of a parameter
// name if the path was an array.
if (pathMatches[i+1] !== undefined || routeParams[self.keys[i].name] === undefined){
routeParams[self.keys[i].name] = pathMatches[i+1];
}
}
// 4. query params
var queryParams = {};
if (-1 !== pos) {
queryParams = queryString.parse(url.substring(pos));
}
return {
route: routeParams,
query: queryParams
};
};
/**
* Generates a path string with this route, using the specified params.
* @method makePath
* @param {Object} params The route parameters to be used to create the path string
* @return {String} The generated path string.
* @for Route
*/
Route.prototype.makePath = function (params, query) {
var routePath = this.config.path;
var compiler;
var err;
var url;
if (Array.isArray(routePath)) {
routePath = routePath[0];
}
if (typeof routePath === 'string') {
compiler = cachedCompilers[routePath] || pathToRegexp.compile(routePath);
cachedCompilers[routePath] = compiler;
try {
url = compiler(params);
if (query) {
url += '?' + queryString.stringify(query);
}
return url;
} catch (e) {
err = e;
}
} else {
err = new TypeError('route path must be a string:' + routePath);
}
debug('Route.makePath failed, e = ', err);
return null;
};
/**
* A Router class that provides route matching and route generation functionalities.
* @class Router
* @param {Object} routes Route table, which is a name to router config map.
* @constructor
* @example
var Router = require('routr'),
router,
route;
var router = new Router({
view_user: {
path: '/user/:id',
method: 'get',
foo: {
bar: 'baz'
}
}
});
route = router.getRoute('/user/garfield');
if (route) {
// this will output:
// - "view_user" for route.name
// - "/user/garfield" for route.url
// - {id: "garfield"} for route.params
// - {path: "/user/:id", method: "get", foo: { bar: "baz"}} for route.config
console.log('[Route found]: name=', route.name, 'url=', route.url, 'params=', route.params, 'config=', route.config);
}
*/
function Router(routes) {
var self = this;
self._routes = {};
self._routeOrder = [];
debug('new Router, routes = ', routes);
if (!Array.isArray(routes)) {
// Support handling route config object as an ordered map (legacy)
self._routeOrder = Object.keys(routes);
self._routeOrder.forEach(function createRoute(name) {
self._routes[name] = new Route(name, routes[name]);
});
} else if (routes) {
routes.forEach(function createRouteFromArrayValue(route) {
if (!route.name) {
throw new Error('Undefined route name for route ' + route.path);
}
// Route name already exists
if (self._routes[route.name]) {
throw new Error('Duplicate route with name ' + route.name);
}
self._routeOrder.push(route.name);
self._routes[route.name] = new Route(route.name, route);
});
}
if (process.env.NODE_ENV !== 'production') {
if ('function' === typeof Object.freeze) {
self._routeOrder.forEach(function freezeRoute(name) {
var route = self._routes[name];
Object.freeze(route.config);
Object.freeze(route.keys);
Object.freeze(route);
});
Object.freeze(self._routes);
}
}
}
/**
* @method getRoute
* @param {String} url The url to be used for route matching. Query strings are **not** considered
* when performing the match. E.g. /some_path?foo=bar would match to the same route
* as /some_path
* @param {Object} [options]
* @param {String} [options.method=get] The case-insensitive HTTP method string.
* @return {Object|null} The matched route info if path/method matches to a route; null otherwise.
*/
Router.prototype.getRoute = function (url, options) {
var keys = this._routeOrder;
var route;
var match;
for (var i = 0, len = keys.length; i < len; i++) {
route = this._routes[keys[i]];
match = route.match(url, options);
if (match) {
return {
name: keys[i],
url: url,
params: match.route,
config: route.config,
query: match.query
};
}
}
return null;
};
/**
* Generates a path string with the route with the given name, using the specified params.
* @method makePath
* @param {String} name The route name
* @param {Object} params The route parameters to be used to create the path string
* @param {Object} query The query parameters to be used to create the path string
* @return {String} The generated path string, null if there is no route with the given name.
*/
Router.prototype.makePath = function (name, params, query) {
return (name && this._routes[name] && this._routes[name].makePath(params, query)) || null;
};
module.exports = Router;