| [9af201e] | 1 | "use strict";
|
|---|
| 2 | Object.defineProperty(exports, "__esModule", { value: true });
|
|---|
| 3 | exports.createPathRewriter = void 0;
|
|---|
| 4 | const isPlainObj = require("is-plain-obj");
|
|---|
| 5 | const errors_1 = require("./errors");
|
|---|
| 6 | const logger_1 = require("./logger");
|
|---|
| 7 | const logger = (0, logger_1.getInstance)();
|
|---|
| 8 | /**
|
|---|
| 9 | * Create rewrite function, to cache parsed rewrite rules.
|
|---|
| 10 | *
|
|---|
| 11 | * @param {Object} rewriteConfig
|
|---|
| 12 | * @return {Function} Function to rewrite paths; This function should accept `path` (request.url) as parameter
|
|---|
| 13 | */
|
|---|
| 14 | function createPathRewriter(rewriteConfig) {
|
|---|
| 15 | let rulesCache;
|
|---|
| 16 | if (!isValidRewriteConfig(rewriteConfig)) {
|
|---|
| 17 | return;
|
|---|
| 18 | }
|
|---|
| 19 | if (typeof rewriteConfig === 'function') {
|
|---|
| 20 | const customRewriteFn = rewriteConfig;
|
|---|
| 21 | return customRewriteFn;
|
|---|
| 22 | }
|
|---|
| 23 | else {
|
|---|
| 24 | rulesCache = parsePathRewriteRules(rewriteConfig);
|
|---|
| 25 | return rewritePath;
|
|---|
| 26 | }
|
|---|
| 27 | function rewritePath(path) {
|
|---|
| 28 | let result = path;
|
|---|
| 29 | for (const rule of rulesCache) {
|
|---|
| 30 | if (rule.regex.test(path)) {
|
|---|
| 31 | result = result.replace(rule.regex, rule.value);
|
|---|
| 32 | logger.debug('[HPM] Rewriting path from "%s" to "%s"', path, result);
|
|---|
| 33 | break;
|
|---|
| 34 | }
|
|---|
| 35 | }
|
|---|
| 36 | return result;
|
|---|
| 37 | }
|
|---|
| 38 | }
|
|---|
| 39 | exports.createPathRewriter = createPathRewriter;
|
|---|
| 40 | function isValidRewriteConfig(rewriteConfig) {
|
|---|
| 41 | if (typeof rewriteConfig === 'function') {
|
|---|
| 42 | return true;
|
|---|
| 43 | }
|
|---|
| 44 | else if (isPlainObj(rewriteConfig)) {
|
|---|
| 45 | return Object.keys(rewriteConfig).length !== 0;
|
|---|
| 46 | }
|
|---|
| 47 | else if (rewriteConfig === undefined || rewriteConfig === null) {
|
|---|
| 48 | return false;
|
|---|
| 49 | }
|
|---|
| 50 | else {
|
|---|
| 51 | throw new Error(errors_1.ERRORS.ERR_PATH_REWRITER_CONFIG);
|
|---|
| 52 | }
|
|---|
| 53 | }
|
|---|
| 54 | function parsePathRewriteRules(rewriteConfig) {
|
|---|
| 55 | const rules = [];
|
|---|
| 56 | if (isPlainObj(rewriteConfig)) {
|
|---|
| 57 | for (const [key] of Object.entries(rewriteConfig)) {
|
|---|
| 58 | rules.push({
|
|---|
| 59 | regex: new RegExp(key),
|
|---|
| 60 | value: rewriteConfig[key],
|
|---|
| 61 | });
|
|---|
| 62 | logger.info('[HPM] Proxy rewrite rule created: "%s" ~> "%s"', key, rewriteConfig[key]);
|
|---|
| 63 | }
|
|---|
| 64 | }
|
|---|
| 65 | return rules;
|
|---|
| 66 | }
|
|---|