UNPKG

@remcostoeten/fync

Version:

A unified TypeScript library for easy access to popular APIs (GitHub, Spotify, GitLab, etc.)

92 lines 3.23 kB
function createHttpClient(config) { const { baseUrl, defaultHeaders = {}, timeout = 30000 } = config; async function makeRequest(path, options = {}, params) { const url = new URL(path, baseUrl); if (params) { for (const [key, value] of Object.entries(params)) { url.searchParams.set(key, String(value)); } } const controller = new AbortController(); function abortRequest() { controller.abort(); } const timeoutId = setTimeout(abortRequest, timeout); try { const response = await fetch(url.toString(), { ...options, headers: { ...defaultHeaders, ...options.headers, }, signal: controller.signal, }); clearTimeout(timeoutId); const responseHeaders = {}; function collectHeaders(value, key) { responseHeaders[key] = value; } response.headers.forEach(collectHeaders); let data; const contentType = response.headers.get("content-type"); if (contentType?.includes("application/json")) { data = await response.json(); } else { data = (await response.text()); } if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } return { data, status: response.status, statusText: response.statusText, headers: responseHeaders, ok: response.ok, }; } catch (error) { clearTimeout(timeoutId); if (error instanceof Error) { throw new Error(`Request failed: ${error.message}`); } throw error; } } return { async get(path, params) { return makeRequest(path, { method: "GET" }, params); }, async post(path, data) { return makeRequest(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: data ? JSON.stringify(data) : undefined, }); }, async put(path, data) { return makeRequest(path, { method: "PUT", headers: { "Content-Type": "application/json" }, body: data ? JSON.stringify(data) : undefined, }); }, async patch(path, data) { return makeRequest(path, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: data ? JSON.stringify(data) : undefined, }); }, async delete(path, data) { return makeRequest(path, { method: "DELETE", headers: data ? { "Content-Type": "application/json" } : {}, body: data ? JSON.stringify(data) : undefined, }); }, }; } export { createHttpClient }; //# sourceMappingURL=http-client.js.map