torc-api
Version:
torc-api is a lightweight wrapper to simplify HTTP requests
96 lines (95 loc) • 2.97 kB
JavaScript
import { Data } from './Data.js';
export class API {
constructor(props) {
Object.defineProperty(this, "url", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "defaultHeaders", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "defaultOptions", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.url = props.url;
this.defaultHeaders = props.headers ?? {};
this.defaultOptions = {
formatToJSON: false,
abortSeconds: 20,
...props.options
};
}
_getParsedUrl(endpoint) {
if (!endpoint)
return '/';
const parsedEndpoint = endpoint.charAt(0) === '/' ? endpoint.slice(1) : endpoint;
return `${this.url}/${parsedEndpoint}`;
}
async _fetch(method, options) {
const controller = new AbortController();
const url = this._getParsedUrl(options.endpoint);
const timeout = setTimeout(() => controller.abort(), this.defaultOptions.abortSeconds * 1000);
const fetchHeaders = { ...this.defaultHeaders, ...options.headers };
const fetchOptions = { ...this.defaultHeaders, ...options };
try {
const response = await fetch(url, {
headers: fetchHeaders,
method,
signal: controller.signal,
...fetchOptions
});
clearTimeout(timeout);
if (!response.ok) {
return Data.failure(response.statusText);
}
if (options.formatToJSON) {
return await response.json();
}
else {
return response;
}
}
catch (error) {
return Data.failure(String(error));
}
}
_execute(method, options) {
const formatToJSON = options.formatToJSON ?? this.defaultOptions.formatToJSON;
const opts = { ...options, formatToJSON };
if (formatToJSON) {
return this._fetch(method, opts);
}
else {
return this._fetch(method, opts);
}
}
async get(options) {
return this._execute('GET', options);
}
async post(options) {
return this._execute('POST', options);
}
async delete(options) {
return this._execute('DELETE', options);
}
async patch(options) {
return this._execute('PATCH', options);
}
async options(options) {
return this._execute('OPTIONS', options);
}
async put(options) {
return this._execute('PUT', options);
}
async head(options) {
return this._execute('HEAD', options);
}
}