UI for Zipcoin Blue

path-rewriter.js 2.0KB

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