UNPKG

@datastax/astra-db-ts

Version:
65 lines (64 loc) 2.11 kB
// Copyright Datastax, Inc // SPDX-License-Identifier: Apache-2.0 // noinspection ExceptionCaughtLocallyJS export class FetchH2 { constructor(options) { Object.defineProperty(this, "_http1", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "_preferred", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "_timeoutErrorCls", { enumerable: true, configurable: true, writable: true, value: void 0 }); const fetchH2 = options.fetchH2; this._http1 = fetchH2.context({ http1: { keepAlive: options.http1?.keepAlive, keepAliveMsecs: options.http1?.keepAliveMS, maxSockets: options.http1?.maxSockets, maxFreeSockets: options.http1?.maxFreeSockets, }, httpsProtocols: ['http1'], }); this._preferred = (options.preferHttp2 ?? true) ? fetchH2.context() : this._http1; this._timeoutErrorCls = fetchH2.TimeoutError; } async fetch(init) { try { const resp = (init.forceHttp1) ? await this._http1.fetch(init.url, init) : await this._preferred.fetch(init.url, init); return { headers: Object.fromEntries(resp.headers.entries()), body: await resp.text(), status: resp.status, url: resp.url, httpVersion: resp.httpVersion, statusText: resp.statusText, }; } catch (e) { if (e instanceof this._timeoutErrorCls) { throw init.mkTimeoutError(); } throw e; } } async close() { await this._preferred.disconnectAll(); await this._http1.disconnectAll(); } }