1 | var _ = require('lodash');
|
2 | var logger = require('./logger').getInstance();
|
3 |
|
4 | module.exports = {
|
5 | create: createPathRewriter
|
6 | };
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | function createPathRewriter(rewriteConfig) {
|
14 | var rulesCache;
|
15 |
|
16 | if (!isValidRewriteConfig(rewriteConfig)) {
|
17 | return;
|
18 | }
|
19 |
|
20 | if (_.isFunction(rewriteConfig)) {
|
21 | var customRewriteFn = rewriteConfig;
|
22 | return customRewriteFn;
|
23 | } else {
|
24 | rulesCache = parsePathRewriteRules(rewriteConfig);
|
25 | return rewritePath;
|
26 | }
|
27 |
|
28 | function rewritePath(path) {
|
29 | var result = path;
|
30 |
|
31 | _.forEach(rulesCache, function(rule) {
|
32 | if (rule.regex.test(path)) {
|
33 | result = result.replace(rule.regex, rule.value);
|
34 | logger.debug('[HPM] Rewriting path from "%s" to "%s"', path, result);
|
35 | return false;
|
36 | }
|
37 | });
|
38 |
|
39 | return result;
|
40 | }
|
41 | }
|
42 |
|
43 | function isValidRewriteConfig(rewriteConfig) {
|
44 | if (_.isFunction(rewriteConfig)) {
|
45 | return true;
|
46 | } else if (!_.isEmpty(rewriteConfig) && _.isPlainObject(rewriteConfig)) {
|
47 | return true;
|
48 | } else if (_.isUndefined(rewriteConfig) ||
|
49 | _.isNull(rewriteConfig) ||
|
50 | _.isEqual(rewriteConfig, {})) {
|
51 | return false;
|
52 | } else {
|
53 | throw new Error('[HPM] Invalid pathRewrite config. Expecting object with pathRewrite config or a rewrite function');
|
54 | }
|
55 | }
|
56 |
|
57 | function parsePathRewriteRules(rewriteConfig) {
|
58 | var rules = [];
|
59 |
|
60 | if (_.isPlainObject(rewriteConfig)) {
|
61 | _.forIn(rewriteConfig, function(value, key) {
|
62 | rules.push({
|
63 | regex: new RegExp(key),
|
64 | value: rewriteConfig[key]
|
65 | });
|
66 | logger.info('[HPM] Proxy rewrite rule created: "%s" ~> "%s"', key, rewriteConfig[key]);
|
67 | });
|
68 | }
|
69 |
|
70 | return rules;
|
71 | }
|
72 |
|