uniapp,h5

polling-fetch.js 1.8KB

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