| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- import isPlainObject from 'is-plain-obj';
- import { Debug } from './debug.js';
- import { HttpProxyMiddlewareError } from './errors.js';
- const debug = Debug.extend('path-rewriter');
- /**
- * Create rewrite function, to cache parsed rewrite rules.
- */
- export function createPathRewriter(rewriteConfig) {
- let rulesCache;
- if (!isValidRewriteConfig(rewriteConfig)) {
- return;
- }
- if (typeof rewriteConfig === 'function') {
- const customRewriteFn = rewriteConfig;
- return customRewriteFn;
- }
- else {
- rulesCache = parsePathRewriteRules(rewriteConfig);
- return rewritePath;
- }
- function rewritePath(path) {
- let result = path;
- for (const rule of rulesCache) {
- if (rule.regex.test(path)) {
- result = result.replace(rule.regex, rule.value);
- debug('rewriting path from "%s" to "%s"', path, result);
- break;
- }
- }
- return result;
- }
- }
- function isValidRewriteConfig(rewriteConfig) {
- if (typeof rewriteConfig === 'function') {
- return true;
- }
- else if (isPlainObject(rewriteConfig)) {
- return Object.keys(rewriteConfig).length !== 0;
- }
- else if (rewriteConfig === undefined || rewriteConfig === null) {
- return false;
- }
- else {
- throw new HttpProxyMiddlewareError('[HPM] Invalid pathRewrite config. Expecting object with pathRewrite config or a rewrite function', 'HPM_INVALID_PATH_REWRITER_CONFIG');
- }
- }
- function parsePathRewriteRules(rewriteConfig) {
- const rules = [];
- if (isPlainObject(rewriteConfig)) {
- for (const [key, value] of Object.entries(rewriteConfig)) {
- rules.push({
- regex: new RegExp(key),
- value: value,
- });
- debug('rewrite rule created: "%s" ~> "%s"', key, value);
- }
- }
- return rules;
- }
|