router.js 1.3 KB

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