path-rewriter.js 1.8 KB

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