You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
2.0 KiB
60 lines
2.0 KiB
"use strict"; |
|
Object.defineProperty(exports, "__esModule", { value: true }); |
|
exports.Fetch = void 0; |
|
const polling_js_1 = require("./polling.js"); |
|
/** |
|
* HTTP long-polling based on the built-in `fetch()` method. |
|
* |
|
* Usage: browser, Node.js (since v18), Deno, Bun |
|
* |
|
* @see https://developer.mozilla.org/en-US/docs/Web/API/fetch |
|
* @see https://caniuse.com/fetch |
|
* @see https://nodejs.org/api/globals.html#fetch |
|
*/ |
|
class Fetch extends polling_js_1.Polling { |
|
doPoll() { |
|
this._fetch() |
|
.then((res) => { |
|
if (!res.ok) { |
|
return this.onError("fetch read error", res.status, res); |
|
} |
|
res.text().then((data) => this.onData(data)); |
|
}) |
|
.catch((err) => { |
|
this.onError("fetch read error", err); |
|
}); |
|
} |
|
doWrite(data, callback) { |
|
this._fetch(data) |
|
.then((res) => { |
|
if (!res.ok) { |
|
return this.onError("fetch write error", res.status, res); |
|
} |
|
callback(); |
|
}) |
|
.catch((err) => { |
|
this.onError("fetch write error", err); |
|
}); |
|
} |
|
_fetch(data) { |
|
var _a; |
|
const isPost = data !== undefined; |
|
const headers = new Headers(this.opts.extraHeaders); |
|
if (isPost) { |
|
headers.set("content-type", "text/plain;charset=UTF-8"); |
|
} |
|
(_a = this.socket._cookieJar) === null || _a === void 0 ? void 0 : _a.appendCookies(headers); |
|
return fetch(this.uri(), { |
|
method: isPost ? "POST" : "GET", |
|
body: isPost ? data : null, |
|
headers, |
|
credentials: this.opts.withCredentials ? "include" : "omit", |
|
}).then((res) => { |
|
var _a; |
|
// @ts-ignore getSetCookie() was added in Node.js v19.7.0 |
|
(_a = this.socket._cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(res.headers.getSetCookie()); |
|
return res; |
|
}); |
|
} |
|
} |
|
exports.Fetch = Fetch;
|
|
|