webclient-fetch.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. return new (P || (P = Promise))(function (resolve, reject) {
  4. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  5. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  6. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  7. step((generator = generator.apply(thisArg, _arguments || [])).next());
  8. });
  9. };
  10. Object.defineProperty(exports, "__esModule", { value: true });
  11. class WebClientFetch {
  12. request(options) {
  13. return __awaiter(this, void 0, void 0, function* () {
  14. const fetchOptions = {
  15. headers: options.headers,
  16. method: options.method
  17. };
  18. if (options.body) {
  19. fetchOptions.body = options.body;
  20. }
  21. const res = yield fetch(options.url, fetchOptions);
  22. if (!res.ok) {
  23. console.error('HTTP error', res);
  24. throw new Error('Error ' + res.status + ' returned from ' + options.url);
  25. }
  26. // console.log('res', res);
  27. return res.text();
  28. });
  29. }
  30. requestJSON(options) {
  31. return __awaiter(this, void 0, void 0, function* () {
  32. if (!options.headers) {
  33. options.headers = {};
  34. }
  35. if (options.body) {
  36. options.headers['content-type'] = 'application/json';
  37. if (typeof options.body === 'object') {
  38. options.body = JSON.stringify(options.body);
  39. }
  40. }
  41. options.headers.accept = 'application/json';
  42. const fetchOptions = {
  43. headers: options.headers,
  44. method: options.method
  45. };
  46. if (options.formData) {
  47. fetchOptions.formData = options.formData;
  48. }
  49. if (options.body) {
  50. fetchOptions.body = options.body;
  51. }
  52. const res = yield fetch(options.url, fetchOptions);
  53. if (!res.ok) {
  54. console.error('HTTP error', res);
  55. throw new Error('Error ' + res.status + ' returned from ' + options.url);
  56. }
  57. // console.log('res', res);
  58. return res.json();
  59. });
  60. }
  61. }
  62. exports.WebClientFetch = WebClientFetch;
  63. //# sourceMappingURL=webclient-fetch.js.map