-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
84 lines (72 loc) · 1.5 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
/**
* Module dependencies.
*/
const debug = require('debug')('express-urlrewrite');
const { pathToRegexp } = require('path-to-regexp');
const URL = require('url');
/**
* Expose `expose`.
*/
module.exports = rewrite;
/**
* Rewrite `src` to `dst`.
*
* @param {String|RegExp} src
* @param {String} dst
* @return {Function}
* @api public
*/
function rewrite(src, dst) {
const keys = [];
let re, map;
if (dst) {
if (typeof src == "string") src = src.replace(/\*/g, '(.*)');
re = pathToRegexp(src, keys);
map = toMap(keys);
debug('rewrite %s -> %s %s', src, dst, re);
} else {
debug('rewrite current route -> %s', src);
}
return function(req, res, next) {
const orig = req.url;
let m;
if (dst) {
m = re.exec(orig);
if (!m) {
return next();
}
}
req.url = (dst || src).replace(/\$(\d+)|(?::(\w+))/g, (_, n, name) => {
if (name) {
if (m) return m[map[name].index + 1];
else return req.params[name];
} else if (m) {
return m[n];
} else {
return req.params[n];
}
});
debug('rewrite %s -> %s', orig, req.url);
if (req.url.indexOf('?') > 0) {
req.query = URL.parse(req.url, true).query;
debug('rewrite updated new query', req.query);
}
if (dst) next();
else next('route');
};
}
/**
* Turn params array into a map for quick lookup.
*
* @param {Array} params
* @return {Object}
* @api private
*/
function toMap(params) {
const map = {};
params.forEach((param, i) => {
param.index = i;
map[param.name] = param;
});
return map;
}