UNPKG

@sky-mavis/tanto-widget

Version:
48 lines 1.45 kB
class RequestError extends Error { status; data; constructor(message, status, data = null) { super(message); this.name = 'RequestError'; this.status = status; this.data = data; } } async function request(url, options = {}) { const { method = 'GET', timeout = 15000, headers = {}, body } = options; const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), timeout); const hasBody = body !== undefined && ['POST', 'PUT', 'PATCH'].includes(method); const fetchOptions = { method, headers: { Accept: 'application/json', ...(hasBody && { 'Content-Type': 'application/json' }), ...headers }, body: hasBody ? JSON.stringify(body) : undefined, signal: controller.signal }; try { const response = await fetch(url, fetchOptions); const responseData = await response.json(); if (!response.ok) throw new RequestError(response.statusText || `HTTP ${response.status}`, response.status, responseData); return responseData; } catch (error) { if (error instanceof RequestError) throw error; if (error instanceof Error) { if (error.name === 'AbortError') throw new RequestError('Request timeout', 408); throw new RequestError(error.message, 0); } throw new RequestError('Unknown error occurred', 0); } finally { clearTimeout(timeoutId); } }export{RequestError,request};