|
| 1 | +import { Polling } from "./polling.js"; |
| 2 | +import { CookieJar, createCookieJar } from "./xmlhttprequest.js"; |
| 3 | + |
| 4 | +/** |
| 5 | + * HTTP long-polling based on `fetch()` |
| 6 | + * |
| 7 | + * @see https://developer.mozilla.org/en-US/docs/Web/API/fetch |
| 8 | + */ |
| 9 | +export class Fetch extends Polling { |
| 10 | + private readonly cookieJar?: CookieJar; |
| 11 | + |
| 12 | + constructor(opts) { |
| 13 | + super(opts); |
| 14 | + |
| 15 | + if (this.opts.withCredentials) { |
| 16 | + this.cookieJar = createCookieJar(); |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + override doPoll() { |
| 21 | + this._fetch() |
| 22 | + .then((res) => { |
| 23 | + if (!res.ok) { |
| 24 | + return this.onError("fetch read error", res.status, res); |
| 25 | + } |
| 26 | + |
| 27 | + res.text().then((data) => this.onData(data)); |
| 28 | + }) |
| 29 | + .catch((err) => { |
| 30 | + this.onError("fetch read error", err); |
| 31 | + }); |
| 32 | + } |
| 33 | + |
| 34 | + override doWrite(data: string, callback: () => void) { |
| 35 | + this._fetch(data) |
| 36 | + .then((res) => { |
| 37 | + if (!res.ok) { |
| 38 | + return this.onError("fetch write error", res.status, res); |
| 39 | + } |
| 40 | + |
| 41 | + callback(); |
| 42 | + }) |
| 43 | + .catch((err) => { |
| 44 | + this.onError("fetch write error", err); |
| 45 | + }); |
| 46 | + } |
| 47 | + |
| 48 | + private _fetch(data?: string) { |
| 49 | + const isPost = data !== undefined; |
| 50 | + const headers = new Headers(this.opts.extraHeaders); |
| 51 | + |
| 52 | + if (isPost) { |
| 53 | + headers.set("content-type", "text/plain;charset=UTF-8"); |
| 54 | + } |
| 55 | + |
| 56 | + this.cookieJar?.appendCookies(headers); |
| 57 | + |
| 58 | + return fetch(this.uri(), { |
| 59 | + method: isPost ? "POST" : "GET", |
| 60 | + body: isPost ? data : null, |
| 61 | + headers, |
| 62 | + credentials: this.opts.withCredentials ? "include" : "omit", |
| 63 | + }).then((res) => { |
| 64 | + if (this.cookieJar) { |
| 65 | + // @ts-ignore getSetCookie() was added in Node.js v19.7.0 |
| 66 | + this.cookieJar.parseCookies(res.headers.getSetCookie()); |
| 67 | + } |
| 68 | + |
| 69 | + return res; |
| 70 | + }); |
| 71 | + } |
| 72 | +} |
0 commit comments