@remcostoeten/fync
Version:
A unified TypeScript library for easy access to popular APIs (GitHub, Spotify, GitLab, etc.)
93 lines • 3.03 kB
JavaScript
export function createHttpClient(config) {
const cache = new Map();
function getCacheKey(url, options = {}) {
return `${url}:${JSON.stringify(options)}`;
}
function isExpired(timestamp, ttl) {
return Date.now() - timestamp > ttl;
}
function getFromCache(key) {
const cached = cache.get(key);
if (!cached)
return null;
if (isExpired(cached.timestamp, cached.ttl)) {
cache.delete(key);
return null;
}
return cached.data;
}
function setCache(key, data, ttl) {
cache.set(key, {
data,
timestamp: Date.now(),
ttl,
});
}
async function makeRequest(url, method, data, options = {}) {
const shouldCache = options.cache !== false && config.cache !== false;
const cacheTTL = options.cacheTTL || config.cacheTTL || 300000; // 5 minutes default
if (shouldCache && method === "GET") {
const cacheKey = getCacheKey(url, options);
const cached = getFromCache(cacheKey);
if (cached)
return cached;
}
const fetchOptions = {
method,
headers: {
"Content-Type": "application/json",
...options.headers,
},
};
if (data &&
(method === "POST" || method === "PUT" || method === "DELETE")) {
fetchOptions.body = JSON.stringify(data);
}
const response = await fetch(url, fetchOptions);
if (!response.ok) {
let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
try {
const errorData = (await response.json());
if (errorData.error) {
if (typeof errorData.error === "string") {
errorMessage = errorData.error;
}
else {
errorMessage = errorData.error.message || "Unknown error";
}
}
}
catch {
}
throw new Error(errorMessage);
}
if (response.status === 204) {
return undefined;
}
const result = (await response.json());
if (shouldCache && method === "GET") {
const cacheKey = getCacheKey(url, options);
setCache(cacheKey, result, cacheTTL);
}
return result;
}
function get(url, options) {
return makeRequest(url, "GET", undefined, options);
}
function post(url, data, options) {
return makeRequest(url, "POST", data, options);
}
function put(url, data, options) {
return makeRequest(url, "PUT", data, options);
}
function deleteRequest(url, data, options) {
return makeRequest(url, "DELETE", data, options);
}
return {
get,
post,
put,
delete: deleteRequest,
};
}
//# sourceMappingURL=http.js.map