UNPKG

@bsv/sdk

Version:

BSV Blockchain Software Development Kit

90 lines 2.86 kB
/** * Adapter for Node Https module to be used as HttpClient */ export class BinaryNodejsHttpClient { https; constructor(https) { this.https = https; } async request(url, requestOptions) { return await new Promise((resolve, reject) => { const req = this.https.request(url, requestOptions, (res) => { let body = ''; res.on('data', (chunk) => { body += chunk; }); res.on('end', () => { const ok = res.statusCode >= 200 && res.statusCode <= 299; const mediaType = res.headers['content-type']; const data = body !== '' && typeof mediaType === 'string' && mediaType.startsWith('application/json') ? JSON.parse(body) : body; resolve({ status: res.statusCode, statusText: res.statusMessage, ok, data }); }); }); req.on('error', (error) => { reject(error); }); if (requestOptions.data !== null && requestOptions.data !== undefined) { req.write(Buffer.from(requestOptions.data)); } req.end(); }); } } /** * Adapter for Node Https module to be used as HttpClient */ export class BinaryFetchClient { fetch; constructor(fetch) { this.fetch = fetch; } async request(url, options) { const fetchOptions = { method: options.method, headers: options.headers, body: options.data }; const res = await this.fetch(url, fetchOptions); const data = await res.text(); return { ok: res.ok, status: res.status, statusText: res.statusText, data: data }; } } export function binaryHttpClient() { const noHttpClient = { async request(..._) { throw new Error('No method available to perform HTTP request'); } }; if (typeof window !== 'undefined' && typeof window.fetch === 'function') { // Use fetch in a browser environment return new BinaryFetchClient(window.fetch.bind(window)); } else if (typeof require !== 'undefined') { // Use Node https module // eslint-disable-next-line try { // eslint-disable-next-line @typescript-eslint/no-var-requires const https = require('https'); return new BinaryNodejsHttpClient(https); } catch (e) { return noHttpClient; } } else { return noHttpClient; } } //# sourceMappingURL=BinaryFetchClient.js.map