| 1 | "use strict";
|
|---|
| 2 | Object.defineProperty(exports, "__esModule", { value: true });
|
|---|
| 3 | exports.getTarget = void 0;
|
|---|
| 4 | const isPlainObj = require("is-plain-obj");
|
|---|
| 5 | const logger_1 = require("./logger");
|
|---|
| 6 | const logger = (0, logger_1.getInstance)();
|
|---|
| 7 | async function getTarget(req, config) {
|
|---|
| 8 | let newTarget;
|
|---|
| 9 | const router = config.router;
|
|---|
| 10 | if (isPlainObj(router)) {
|
|---|
| 11 | newTarget = getTargetFromProxyTable(req, router);
|
|---|
| 12 | }
|
|---|
| 13 | else if (typeof router === 'function') {
|
|---|
| 14 | newTarget = await router(req);
|
|---|
| 15 | }
|
|---|
| 16 | return newTarget;
|
|---|
| 17 | }
|
|---|
| 18 | exports.getTarget = getTarget;
|
|---|
| 19 | function getTargetFromProxyTable(req, table) {
|
|---|
| 20 | let result;
|
|---|
| 21 | const host = req.headers.host;
|
|---|
| 22 | const path = req.url;
|
|---|
| 23 | const hostAndPath = host + path;
|
|---|
| 24 | for (const [key] of Object.entries(table)) {
|
|---|
| 25 | if (containsPath(key)) {
|
|---|
| 26 | if (hostAndPath.indexOf(key) > -1) {
|
|---|
| 27 | // match 'localhost:3000/api'
|
|---|
| 28 | result = table[key];
|
|---|
| 29 | logger.debug('[HPM] Router table match: "%s"', key);
|
|---|
| 30 | break;
|
|---|
| 31 | }
|
|---|
| 32 | }
|
|---|
| 33 | else {
|
|---|
| 34 | if (key === host) {
|
|---|
| 35 | // match 'localhost:3000'
|
|---|
| 36 | result = table[key];
|
|---|
| 37 | logger.debug('[HPM] Router table match: "%s"', host);
|
|---|
| 38 | break;
|
|---|
| 39 | }
|
|---|
| 40 | }
|
|---|
| 41 | }
|
|---|
| 42 | return result;
|
|---|
| 43 | }
|
|---|
| 44 | function containsPath(v) {
|
|---|
| 45 | return v.indexOf('/') > -1;
|
|---|
| 46 | }
|
|---|