UNPKG

sefetch

Version:

A highly advanced fetch module with caching, retry, and timeout features.

91 lines (76 loc) 2.7 kB
class sefetch { constructor(baseURL = '', timeout = 5000, retries = 3, cache = false) { this.baseURL = baseURL; this.timeout = timeout; this.retries = retries; this.cache = cache; this.cacheStore = new Map(); this.defaultHeaders = {}; } async request(url, options = {}, attempt = 1) { const fullURL = this.baseURL ? `${this.baseURL}${url}` : url; if (this.cache && this.cacheStore.has(fullURL)) { return this.cacheStore.get(fullURL); } const controller = new AbortController(); const id = setTimeout(() => controller.abort(), this.timeout); const config = { ...options, signal: controller.signal, headers: { ...this.defaultHeaders, ...options.headers } }; try { const response = await fetch(fullURL, config); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } let data; const contentType = response.headers.get('Content-Type'); if (contentType.includes('application/json')) { data = await response.json(); } else if (contentType.includes('text/xml')) { data = await response.text(); // veya XML parsing } else { data = await response.text(); } if (this.cache) { this.cacheStore.set(fullURL, data); } return data; } catch (error) { if (error.name === 'AbortError') { console.error('Fetch request timed out'); } else { console.error(`Attempt ${attempt} failed:`, error); } if (attempt < this.retries) { return this.request(url, options, attempt + 1); } throw error; } finally { clearTimeout(id); } } get(url, options = {}) { return this.request(url, { ...options, method: 'GET' }); } post(url, body, options = {}) { return this.request(url, { ...options, method: 'POST', body: JSON.stringify(body) }); } put(url, body, options = {}) { return this.request(url, { ...options, method: 'PUT', body: JSON.stringify(body) }); } delete(url, options = {}) { return this.request(url, { ...options, method: 'DELETE' }); } clearCache() { this.cacheStore.clear(); } getCacheSize() { return this.cacheStore.size; } setHeaders(headers) { this.defaultHeaders = headers; } } module.exports = sefetch;