@tokenizer/http
Version:
HTTP tokenizer for Node.js and browser
45 lines • 1.72 kB
JavaScript
import initDebug from 'debug';
import { ResponseInfo } from './response-info.js'; // Add 'fetch' API for node.js
const debug = initDebug('streaming-http-token-reader:http-client');
const DEFAULT_CONFIG = {
resolveUrl: false
};
/**
* Simple HTTP-client, which works both in node.js and browser
*/
export class HttpClient {
constructor(url, config) {
this.url = url;
this.abortController = new AbortController();
this.config = DEFAULT_CONFIG;
Object.assign(this.config, config);
}
async getHeadInfo() {
const response = new ResponseInfo(await fetch(this.url, { method: 'HEAD', signal: this.abortController.signal }));
if (this.config.resolveUrl)
this.resolvedUrl = response.response.url;
return response.toRangeRequestResponse();
}
async getResponse(method, range) {
const headers = new Headers();
if (range) {
debug(`_getResponse ${method} ${range[0]}..${range[1]}`);
headers.set('Range', `bytes=${range[0]}-${range[1]}`);
}
else {
debug(`_getResponse ${method} (range not provided)`);
}
const response = new ResponseInfo(await fetch(this.resolvedUrl || this.url, { method, headers, signal: this.abortController.signal }));
if (response.response.ok) {
if (this.config.resolveUrl)
this.resolvedUrl = response.response.url;
return response.toRangeRequestResponse();
}
throw new Error(`Unexpected HTTP response status=${response.response.status}`);
}
abort() {
debug('abort');
this.abortController.abort();
}
}
//# sourceMappingURL=http-client.js.map