UNPKG

query-harbor

Version:

A React Query utility package for efficient data fetching and caching

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