router.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  4. return new (P || (P = Promise))(function (resolve, reject) {
  5. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  7. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9. });
  10. };
  11. Object.defineProperty(exports, "__esModule", { value: true });
  12. exports.getTarget = void 0;
  13. const isPlainObj = require("is-plain-obj");
  14. const logger_1 = require("./logger");
  15. const logger = logger_1.getInstance();
  16. function getTarget(req, config) {
  17. return __awaiter(this, void 0, void 0, function* () {
  18. let newTarget;
  19. const router = config.router;
  20. if (isPlainObj(router)) {
  21. newTarget = getTargetFromProxyTable(req, router);
  22. }
  23. else if (typeof router === 'function') {
  24. newTarget = yield router(req);
  25. }
  26. return newTarget;
  27. });
  28. }
  29. exports.getTarget = getTarget;
  30. function getTargetFromProxyTable(req, table) {
  31. let result;
  32. const host = req.headers.host;
  33. const path = req.url;
  34. const hostAndPath = host + path;
  35. for (const [key] of Object.entries(table)) {
  36. if (containsPath(key)) {
  37. if (hostAndPath.indexOf(key) > -1) {
  38. // match 'localhost:3000/api'
  39. result = table[key];
  40. logger.debug('[HPM] Router table match: "%s"', key);
  41. break;
  42. }
  43. }
  44. else {
  45. if (key === host) {
  46. // match 'localhost:3000'
  47. result = table[key];
  48. logger.debug('[HPM] Router table match: "%s"', host);
  49. break;
  50. }
  51. }
  52. }
  53. return result;
  54. }
  55. function containsPath(v) {
  56. return v.indexOf('/') > -1;
  57. }