@openade/fe
Version:
Fatturazione Elettronica - Electronic Invoicing for Sistema di Interscambio (SDI)
68 lines • 2.66 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpService = void 0;
class HttpService {
async request(config) {
const { url, method = 'GET', headers = {}, body, timeout = 30000, retries = 3 } = config;
let lastError = null;
for (let attempt = 0; attempt <= retries; attempt++) {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
const response = await fetch(url, {
method,
headers: {
'Content-Type': 'application/json',
...headers,
},
body: body ? (typeof body === 'string' ? body : JSON.stringify(body)) : undefined,
signal: controller.signal,
});
clearTimeout(timeoutId);
const responseHeaders = {};
response.headers.forEach((value, key) => {
responseHeaders[key] = value;
});
let data;
const contentType = response.headers.get('content-type');
if (contentType?.includes('application/json')) {
data = await response.json();
}
else {
data = (await response.text());
}
return {
data,
status: response.status,
headers: responseHeaders,
};
}
catch (error) {
lastError = error;
if (attempt < retries) {
const delay = Math.pow(2, attempt) * 1000;
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
}
throw lastError || new Error('HTTP request failed');
}
async get(url, headers) {
const response = await this.request({ url, method: 'GET', headers });
return response.data;
}
async post(url, body, headers) {
const response = await this.request({ url, method: 'POST', body, headers });
return response.data;
}
async put(url, body, headers) {
const response = await this.request({ url, method: 'PUT', body, headers });
return response.data;
}
async delete(url, headers) {
const response = await this.request({ url, method: 'DELETE', headers });
return response.data;
}
}
exports.HttpService = HttpService;
//# sourceMappingURL=http.service.js.map