path-rewriter.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import isPlainObject from 'is-plain-obj';
  2. import { Debug } from './debug.js';
  3. import { HttpProxyMiddlewareError } from './errors.js';
  4. const debug = Debug.extend('path-rewriter');
  5. /**
  6. * Create rewrite function, to cache parsed rewrite rules.
  7. */
  8. export function createPathRewriter(rewriteConfig) {
  9. let rulesCache;
  10. if (!isValidRewriteConfig(rewriteConfig)) {
  11. return;
  12. }
  13. if (typeof rewriteConfig === 'function') {
  14. const customRewriteFn = rewriteConfig;
  15. return customRewriteFn;
  16. }
  17. else {
  18. rulesCache = parsePathRewriteRules(rewriteConfig);
  19. return rewritePath;
  20. }
  21. function rewritePath(path) {
  22. let result = path;
  23. for (const rule of rulesCache) {
  24. if (rule.regex.test(path)) {
  25. result = result.replace(rule.regex, rule.value);
  26. debug('rewriting path from "%s" to "%s"', path, result);
  27. break;
  28. }
  29. }
  30. return result;
  31. }
  32. }
  33. function isValidRewriteConfig(rewriteConfig) {
  34. if (typeof rewriteConfig === 'function') {
  35. return true;
  36. }
  37. else if (isPlainObject(rewriteConfig)) {
  38. return Object.keys(rewriteConfig).length !== 0;
  39. }
  40. else if (rewriteConfig === undefined || rewriteConfig === null) {
  41. return false;
  42. }
  43. else {
  44. throw new HttpProxyMiddlewareError('[HPM] Invalid pathRewrite config. Expecting object with pathRewrite config or a rewrite function', 'HPM_INVALID_PATH_REWRITER_CONFIG');
  45. }
  46. }
  47. function parsePathRewriteRules(rewriteConfig) {
  48. const rules = [];
  49. if (isPlainObject(rewriteConfig)) {
  50. for (const [key, value] of Object.entries(rewriteConfig)) {
  51. rules.push({
  52. regex: new RegExp(key),
  53. value: value,
  54. });
  55. debug('rewrite rule created: "%s" ~> "%s"', key, value);
  56. }
  57. }
  58. return rules;
  59. }