UNPKG

@duongtrungnguyen/next-helper

Version:
83 lines 2.58 kB
import { queryCache } from "./cache"; import { HttpClient } from "../query/http"; import { libConfig } from "../configs"; async function fetchQuery(options) { const { queryKey, queryFn, staleTime = 5 * 60 * 1e3, // 5 minutes cacheTime = 30 * 60 * 1e3, // 30 minutes retry = 3, retryDelay = (attempt) => Math.min(1e3 * 2 ** attempt, 3e4), initialData, select = (data) => data } = options; const cachedData = queryCache.get(queryKey); if (cachedData !== void 0 && !queryCache.isStale(queryKey)) { return select(cachedData); } if (cachedData !== void 0) { const result = select(cachedData); executeQueryAndCache().catch((error) => { console.error("Background fetch error:", error); }); return result; } if (initialData !== void 0 && cachedData === void 0) { const initialValue = typeof initialData === "function" ? initialData() : initialData; if (initialValue !== void 0) { queryCache.set(queryKey, initialValue, staleTime, cacheTime); return select(initialValue); } } return executeQueryAndCache(); async function executeQueryAndCache() { let attempts = 0; const maxRetries = typeof retry === "number" ? retry : retry === true ? 3 : 0; const executeQuery = async () => { try { const result = await queryFn({}, { queryKey }); queryCache.set(queryKey, result, staleTime, cacheTime); return select(result); } catch (error) { if (attempts >= maxRetries) { throw error; } attempts++; const delay = typeof retryDelay === "function" ? retryDelay(attempts) : typeof retryDelay === "number" ? retryDelay : Math.min(1e3 * 2 ** attempts, 3e4); await new Promise((resolve) => setTimeout(resolve, delay)); return executeQuery(); } }; return executeQuery(); } } function createQueryFn(url, params) { return async () => { const http = new HttpClient(url.includes("http") ? "" : libConfig.baseUrl); return http.get(url, { query: params }); }; } async function prefetchQuery(options) { try { await fetchQuery(options); } catch (error) { console.error("Error prefetching query:", error); } } function getQueryData(queryKey) { return queryCache.get(queryKey); } function setQueryData(queryKey, data, staleTime = 5 * 60 * 1e3, cacheTime = 30 * 60 * 1e3) { queryCache.set(queryKey, data, staleTime, cacheTime); } export { createQueryFn, fetchQuery, getQueryData, prefetchQuery, setQueryData }; //# sourceMappingURL=server.js.map