-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
51 lines (40 loc) · 1.36 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
var isObject = require('lodash.isobject');
var globject = require('globject');
var pathematics = require('pathematics');
var toxic = require('toxic');
var slasher = require('glob-slasher');
var isUrl = require('is-url');
module.exports = function (redirectRouteMap) {
return function (req, res, next) {
var statusCode = 301;
var normalizedRedirects = slasher(redirectRouteMap);
var redirects = globject(normalizedRedirects);
var redirectUrl = redirects(req.url);
var redirectObj;
// redirect with segments
if (!redirectUrl) {
var parsedUrl = pathematics.withMeta(normalizedRedirects, req.url);
redirectUrl = parsedUrl.url;
statusCode = (parsedUrl.meta && parsedUrl.meta.status) ? parsedUrl.meta.status : statusCode;
}
// redrect from config object
if (isObject(redirectUrl)) {
redirectObj = redirectUrl;
redirectUrl = redirectObj.url;
statusCode = redirectObj.status || statusCode;
}
if (!redirectUrl) {
return next();
}
// Remove leading slash of a url
redirectUrl = formatExternalUrl(redirectUrl);
res.writeHead(statusCode, {Location: redirectUrl});
res.end();
};
};
function formatExternalUrl (u) {
var cleaned = u
.replace('/http:/', 'http://')
.replace('/https:/', 'https://');
return (isUrl(cleaned)) ? cleaned : u;
}