infobip-rtc
Version:
Infobip RTC JavaScript SDK - Infobip WebRTC API Implementation
83 lines • 2.49 kB
JavaScript
const networkErrorMessages = new Set([
'network error',
'Failed to fetch',
'NetworkError when attempting to fetch resource.',
'The Internet connection appears to be offline.',
'Load failed',
'Network request failed',
'fetch failed',
]);
const DEFAULT_NETWORK_ERROR_MESSAGE = "Network error occurred.";
export class NetworkError extends Error {
constructor(message) {
super(message || DEFAULT_NETWORK_ERROR_MESSAGE);
Object.setPrototypeOf(this, NetworkError.prototype);
this.name = 'NetworkError';
}
}
function isNetworkError(error) {
const isValid = error.name === 'TypeError' && typeof error.message === 'string';
if (!isValid) {
return false;
}
if (error.message === 'Load failed') {
return error.stack === undefined;
}
return networkErrorMessages.has(error.message);
}
export class DefaultHttpClient {
constructor(baseURL, headers) {
this.baseURL = baseURL;
this.headers = headers;
}
delete(url, headers) {
return this.request(url, "DELETE", headers);
}
get(url, headers) {
return this.request(url, "GET", headers);
}
post(url, data, headers) {
return this.request(url, "POST", data, headers);
}
put(url, data, headers) {
return this.request(url, "PUT", data, headers);
}
async request(url, method, data, headers) {
const fullPath = this.baseURL + url;
const options = {
method: method
};
if (data != null) {
const isFormData = data instanceof FormData;
options.body = isFormData ? data : JSON.stringify(data);
}
if (this.headers != null || headers != null) {
options.headers = {
...this.headers,
...headers
};
}
try {
const response = await fetch(fullPath, options);
const resultJson = await response.json();
const result = {
statusCode: response.status,
ok: response.ok
};
if (result.ok) {
result.data = resultJson;
}
else {
result.error = resultJson;
}
return result;
}
catch (e) {
if (isNetworkError(e)) {
throw new NetworkError();
}
throw e;
}
}
}
//# sourceMappingURL=HttpClient.js.map