uniapp,h5

polling-fetch.js 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.Fetch = void 0;
  4. const polling_js_1 = require("./polling.js");
  5. /**
  6. * HTTP long-polling based on the built-in `fetch()` method.
  7. *
  8. * Usage: browser, Node.js (since v18), Deno, Bun
  9. *
  10. * @see https://developer.mozilla.org/en-US/docs/Web/API/fetch
  11. * @see https://caniuse.com/fetch
  12. * @see https://nodejs.org/api/globals.html#fetch
  13. */
  14. class Fetch extends polling_js_1.Polling {
  15. doPoll() {
  16. this._fetch()
  17. .then((res) => {
  18. if (!res.ok) {
  19. return this.onError("fetch read error", res.status, res);
  20. }
  21. res.text().then((data) => this.onData(data));
  22. })
  23. .catch((err) => {
  24. this.onError("fetch read error", err);
  25. });
  26. }
  27. doWrite(data, callback) {
  28. this._fetch(data)
  29. .then((res) => {
  30. if (!res.ok) {
  31. return this.onError("fetch write error", res.status, res);
  32. }
  33. callback();
  34. })
  35. .catch((err) => {
  36. this.onError("fetch write error", err);
  37. });
  38. }
  39. _fetch(data) {
  40. var _a;
  41. const isPost = data !== undefined;
  42. const headers = new Headers(this.opts.extraHeaders);
  43. if (isPost) {
  44. headers.set("content-type", "text/plain;charset=UTF-8");
  45. }
  46. (_a = this.socket._cookieJar) === null || _a === void 0 ? void 0 : _a.appendCookies(headers);
  47. return fetch(this.uri(), {
  48. method: isPost ? "POST" : "GET",
  49. body: isPost ? data : null,
  50. headers,
  51. credentials: this.opts.withCredentials ? "include" : "omit",
  52. }).then((res) => {
  53. var _a;
  54. // @ts-ignore getSetCookie() was added in Node.js v19.7.0
  55. (_a = this.socket._cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(res.headers.getSetCookie());
  56. return res;
  57. });
  58. }
  59. }
  60. exports.Fetch = Fetch;