HttpProvider.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const tslib_1 = require("tslib");
  4. const axios_1 = tslib_1.__importDefault(require("axios"));
  5. const validations_js_1 = require("../../utils/validations.js");
  6. class HttpProvider {
  7. host;
  8. timeout;
  9. user;
  10. password;
  11. headers;
  12. statusPage;
  13. instance;
  14. constructor(host, timeout = 30000, user = '', password = '', headers = {}, statusPage = '/') {
  15. if (!(0, validations_js_1.isValidURL)(host))
  16. throw new Error('Invalid URL provided to HttpProvider');
  17. if (isNaN(timeout) || timeout < 0)
  18. throw new Error('Invalid timeout duration provided');
  19. if (!(0, validations_js_1.isObject)(headers))
  20. throw new Error('Invalid headers object provided');
  21. host = host.replace(/\/+$/, '');
  22. this.host = host;
  23. this.timeout = timeout;
  24. this.user = user;
  25. this.password = password;
  26. this.headers = headers;
  27. this.statusPage = statusPage;
  28. this.instance = axios_1.default.create({
  29. baseURL: host,
  30. timeout: timeout,
  31. headers: headers,
  32. auth: user
  33. ? {
  34. username: user,
  35. password,
  36. }
  37. : undefined,
  38. });
  39. }
  40. setStatusPage(statusPage = '/') {
  41. this.statusPage = statusPage;
  42. }
  43. async isConnected(statusPage = this.statusPage) {
  44. return this.request(statusPage)
  45. .then((data) => {
  46. return (0, validations_js_1.hasProperties)(data, 'blockID', 'block_header');
  47. })
  48. .catch(() => false);
  49. }
  50. request(url, payload = {}, method = 'get') {
  51. method = method.toLowerCase();
  52. return this.instance
  53. .request({
  54. data: method == 'post' && Object.keys(payload).length ? payload : null,
  55. params: method == 'get' && payload,
  56. url,
  57. method,
  58. })
  59. .then(({ data }) => data);
  60. }
  61. }
  62. exports.default = HttpProvider;
  63. //# sourceMappingURL=HttpProvider.js.map