source: trip-planner-front/node_modules/http-proxy-middleware/lib/path-rewriter.js@ 6a3a178

Last change on this file since 6a3a178 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.8 KB
Line 
1var _ = require('lodash')
2var logger = require('./logger').getInstance()
3var ERRORS = require('./errors')
4
5module.exports = {
6 create: createPathRewriter
7}
8
9/**
10 * Create rewrite function, to cache parsed rewrite rules.
11 *
12 * @param {Object} rewriteConfig
13 * @return {Function} Function to rewrite paths; This function should accept `path` (request.url) as parameter
14 */
15function createPathRewriter(rewriteConfig) {
16 var rulesCache
17
18 if (!isValidRewriteConfig(rewriteConfig)) {
19 return
20 }
21
22 if (_.isFunction(rewriteConfig)) {
23 var customRewriteFn = rewriteConfig
24 return customRewriteFn
25 } else {
26 rulesCache = parsePathRewriteRules(rewriteConfig)
27 return rewritePath
28 }
29
30 function rewritePath(path) {
31 var result = path
32
33 _.forEach(rulesCache, function(rule) {
34 if (rule.regex.test(path)) {
35 result = result.replace(rule.regex, rule.value)
36 logger.debug('[HPM] Rewriting path from "%s" to "%s"', path, result)
37 return false
38 }
39 })
40
41 return result
42 }
43}
44
45function isValidRewriteConfig(rewriteConfig) {
46 if (_.isFunction(rewriteConfig)) {
47 return true
48 } else if (!_.isEmpty(rewriteConfig) && _.isPlainObject(rewriteConfig)) {
49 return true
50 } else if (
51 _.isUndefined(rewriteConfig) ||
52 _.isNull(rewriteConfig) ||
53 _.isEqual(rewriteConfig, {})
54 ) {
55 return false
56 } else {
57 throw new Error(ERRORS.ERR_PATH_REWRITER_CONFIG)
58 }
59}
60
61function parsePathRewriteRules(rewriteConfig) {
62 var rules = []
63
64 if (_.isPlainObject(rewriteConfig)) {
65 _.forIn(rewriteConfig, function(value, key) {
66 rules.push({
67 regex: new RegExp(key),
68 value: rewriteConfig[key]
69 })
70 logger.info(
71 '[HPM] Proxy rewrite rule created: "%s" ~> "%s"',
72 key,
73 rewriteConfig[key]
74 )
75 })
76 }
77
78 return rules
79}
Note: See TracBrowser for help on using the repository browser.