UNPKG

query-harbor

Version:

A React Query utility package for efficient data fetching and caching

303 lines (302 loc) 8.85 kB
import { useQueryClient as q, useQuery as j, useMutation as b, useInfiniteQuery as z } from "@tanstack/react-query"; import { useCookies as B } from "react-cookie"; import P from "axios"; const S = ({ cookieName: n }) => { const [c, a, w] = B([n]); return { cookie: c, setCookie: a, removeCookie: w }; }, W = async ({ action: n, url: c, data: a, headers: w, baseURL: l }) => { const d = l ? P.create({ baseURL: l }) : P; if (l && d !== P) { const g = l.endsWith("/") && c.startsWith("/") ? `${l}${c.slice(1)}` : `${l}${c}`, o = { headers: w }; switch (n) { case "GET": return await P.get(g, o); case "POST": return await P.post(g, a, o); case "PUT": return await P.put(g, a, o); case "DELETE": return await P.delete(g, { ...o, data: a }); default: throw new Error(`Invalid action: ${n}`); } } const f = { headers: w }; switch (n) { case "GET": return await d.get(c, f); case "POST": return await d.post(c, a, f); case "PUT": return await d.put(c, a, f); case "DELETE": return await d.delete(c, { ...f, data: a }); default: throw new Error(`Invalid action: ${n}`); } }, F = async ({ action: n, url: c, data: a, headers: w, baseURL: l }) => { var d, f, g, o, E, t, x, s, m, i; try { const r = await W({ action: n, url: c, data: a, headers: w, baseURL: l }); return r.status >= 200 && r.status <= 299 ? { status: !0, data: r.data, message: r.data.message || "Success", statusCode: r.status } : { status: !1, error: "API Failed", message: "API Failed", statusCode: r.status }; } catch (r) { return P.isAxiosError(r) ? ((d = r.response) == null || d.status, r.message === "Network Error" ? { status: !1, error: "Network Error", message: "Network Error" } : { status: !1, type: (g = (f = r.response) == null ? void 0 : f.data) == null ? void 0 : g.type, message: ((E = (o = r.response) == null ? void 0 : o.data) == null ? void 0 : E.message) || "An error occurred", error: ((x = (t = r.response) == null ? void 0 : t.data) == null ? void 0 : x.error) || "Unknown error", statusCode: (s = r.response) == null ? void 0 : s.status, errorType: (i = (m = r.response) == null ? void 0 : m.data) == null ? void 0 : i.errorType }) : { status: !1, error: "API Failed", message: "An unexpected error occurred" }; } }, V = ({ url: n, baseUrl: c, queryKey: a, method: w, data: l, enabled: d = !0, staleTime: f = 5 * 60 * 1e3, refetchOnWindowFocus: g = !1, select: o }) => { const E = q(), { cookie: t } = S({ cookieName: "accessToken" }); let x = {}; t != null && t.accessToken && (x = { Authorization: `Bearer ${t.accessToken}` }); const s = j({ queryKey: a, queryFn: async () => { try { const i = await F({ action: w, url: n, data: l, headers: x }); return i != null && i.data ? i.data : { totalCount: 0, data: [] }; } catch (i) { throw console.error("Query Error:", i), i; } }, enabled: d, staleTime: f, refetchOnWindowFocus: g, select: o }); return { refetchQuery: () => { E.invalidateQueries({ queryKey: a }); }, queryData: s.data, isLoading: s.isLoading, isError: s.isError, error: s.error }; }, X = ({ url: n, queriesToInvalidate: c, method: a, data: w = {}, isFormData: l = !1, excludedIndexKeys: d = [], onMutationSuccess: f }) => { const g = q(), { cookie: o } = S({ cookieName: "accessToken" }); let E = {}; o != null && o.accessToken && (E = { Authorization: `Bearer ${o == null ? void 0 : o.accessToken}` }); const t = b({ mutationFn: async ({ isPriorityDataAvailable: s, priorityData: m, url: i = n }) => { const r = s ? m : w; if (l) { let $ = new FormData(); const C = (h, e, u = "", k = {}) => { if (e == null) return; const { excludedIndexKeys: T = [] } = k; Array.isArray(e) ? e.forEach((p, y) => { const M = T.includes(u) ? u : u ? `${u}[${y}]` : `${y}`; p instanceof File ? h.append(u, p) : typeof p == "object" && p !== null ? C(h, p, M, k) : h.append(M, p); }) : typeof e == "object" && e !== null ? e instanceof File ? h.append(u, e) : Object.keys(e).forEach((p) => { const y = e[p], I = u ? `${u}[${p}]` : p; C( h, y, I, k ); }) : e !== "" && e !== void 0 && e !== null && h.append(u, e); }, v = { excludedIndexKeys: d }; Object.keys(r).forEach((h) => { C($, r[h], h, v); }); const { status: A, message: D, data: Q } = await F({ action: a, url: n, data: $, headers: E }); if (A) return { data: Q }; throw new Error( D || "Something went wrong!" ); } else { const { status: $, message: C, data: v } = await F({ action: a, url: i, data: r, headers: E }); if ($) return { data: v }; throw new Error( C || "Something went wrong!" ); } }, onSuccess: ({ data: s }) => { c && g.invalidateQueries({ queryKey: c }), f && f(s); }, onError: (s) => (console.error("Mutation Error:", s), { type: "Error", message: (s == null ? void 0 : s.message) || "Something went wrong!", errorType: s == null ? void 0 : s.errorType }) }); return { runMutation: ({ isPriorityDataAvailable: s, priorityData: m, url: i } = {}) => { try { t.mutate({ isPriorityDataAvailable: s, priorityData: m, url: i }); } catch (r) { console.error("Mutation Execution Error:", r); } }, mutationLoading: t.isPending, mutationData: t.data, mutationError: t.error ? { type: "Error", message: t.error.message, errorType: t.error.errorType } : void 0, isMutationSucceeded: t.isSuccess }; }, Y = ({ url: n, queryKey: c, method: a, data: w, enabled: l = !0, staleTime: d = 5 * 60 * 1e3, // Default: 5 minutes responseDataKey: f = "data" }) => { var r, $, C, v, A, D, Q, h; const g = q(), { cookie: o } = S({ cookieName: "accessToken" }), E = o != null && o.accessToken ? { Authorization: `Bearer ${o.accessToken}` } : void 0, t = z({ queryKey: c, initialPageParam: 1, // @ts-ignore queryFn: async ({ pageParam: e = 1 }) => { try { let u = ""; a === "GET" && (u = n != null && n.includes("?") ? `&page=${e}` : `?page=${e}`); const k = await F({ action: a, url: `${n}${u}`, data: { ...w, page: e }, headers: E }); if (k.status && k.data) { const T = k.data, p = T[f] || [], y = T.pagination, I = T.totalCount, M = T.limit, N = T.page, G = T.totalPages, { data: H, ...O } = T; return y ? { data: p, nextPage: y.page < y.totalPages ? y.page + 1 : void 0, hasMore: y.page < y.totalPages, totalCount: y.totalCount, otherData: O } : { data: p, nextPage: N < G ? N + 1 : void 0, hasMore: N < G, totalCount: I, otherData: O }; } return { totalCount: 0, data: [], hasMore: !1 }; } catch (u) { throw console.error("Query Error:", u), u; } }, getNextPageParam: (e) => e != null && e.hasMore ? e.nextPage : void 0, enabled: l, staleTime: d, refetchOnWindowFocus: !1 }), x = () => g.invalidateQueries({ queryKey: c }), s = (($ = (r = t.data) == null ? void 0 : r.pages) == null ? void 0 : $.flatMap((e) => e == null ? void 0 : e.data)) ?? [], m = ((A = (v = (C = t.data) == null ? void 0 : C.pages) == null ? void 0 : v[0]) == null ? void 0 : A.totalCount) ?? 0, i = ((h = (Q = (D = t.data) == null ? void 0 : D.pages) == null ? void 0 : Q[0]) == null ? void 0 : h.otherData) ?? {}; return { refetchQuery: x, queryData: s, isLoading: t.isLoading, isError: t.isError, error: t.error, fetchNextPage: t.fetchNextPage, hasNextPage: t.hasNextPage, totalCount: m, otherData: i }; }; export { S as useCookie, Y as useGlobalInfiniteQuery, X as useGlobalMutation, V as useGlobalQuery };