-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
68 lines (56 loc) · 1.57 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
/*!
* Express Single Page App Router Middleware
* Dan Motzenbecker <[email protected]>
* MIT Licensed
* 0.0.8
*/
var defaults = {
staticPaths: /^\/(?:javascripts)|(?:js)|(?:stylesheets)|(?:css)|(?:images)|(?:favicon)/,
ignore: /1^/,
extraRoutes: /1^/,
noRoute: function(req, res, next) {
next(req, res);
}
};
module.exports = function(app, options) {
var i, l, key, routes, regexStr;
if (!options) {
options = defaults;
} else {
for (key in defaults) {
if (!defaults.hasOwnProperty(key)) continue;
if (!options[key]) {
options[key] = defaults[key];
} else if ((key === 'staticPaths' || key === 'extraRoutes' || key === 'ignore') &&
Array.isArray(options[key])) {
routes = options[key];
regexStr = '^\\/';
for (i = 0, l = routes.length; i < l; i++) {
regexStr += '(?:' + routes[i] + ')' + (i !== l - 1 ? '|' : '\/');
}
options[key] = new RegExp(regexStr);
}
}
}
return function(req, res, next) {
var routes, i, l, url;
url = req.url;
if (url.slice(-1) !== '/') url += '/';
if (req.xhr || req.method !== 'GET' || url === '/' ||
options.staticPaths.test(url) || options.ignore.test(url)) {
return next();
}
if (options.extraRoutes.test(url)) {
req.url = '/';
return next();
}
routes = app.routes.get;
for (i = 0, l = routes.length; i < l; i++) {
if (routes[i].regexp.test(url)) {
req.url = '/';
return next();
}
}
options.noRoute(req, res, next);
};
};