UNPKG

@sfutureapps/nextquery

Version:

A simple package to api query combine with ReactQuery, Moment and lodash

110 lines (102 loc) 2.55 kB
// src/Query.ts var apiUrl = process.env.NEXT_PUBLIC_API_URL; if (!apiUrl) { throw new Error("NEXT_PUBLIC_API_URL is not defined in the .env file"); } var Post = async ({ endpoint, data, revalidate = 0, isExternalUrl = false }) => { try { const options = { method: "POST", headers: { "Content-Type": "application/json" }, next: { revalidate } }; if (data) { options.body = JSON.stringify(data); } const url = !isExternalUrl ? `${apiUrl}${endpoint}` : endpoint; const response = await fetch(url, options); if (!response.ok) { throw new Error("HTTP error! status: " + response.status); } return response.json(); } catch (error) { } }; var Get = async ({ endpoint, data, revalidate = 0, isExternalUrl = false }) => { try { const options = { method: "GET", headers: { "Content-Type": "application/json" }, next: { revalidate } }; if (data) { options.body = JSON.stringify(data); } const url = !isExternalUrl ? `${apiUrl}${endpoint}` : endpoint; const response = await fetch(url, options); if (!response.ok) { throw new Error("HTTP error! status: " + response.status); } return response.json(); } catch (error) { return error; } }; // src/ReactQuery.ts import { useMutation, useQuery } from "@tanstack/react-query"; var Mutate = ({ key, endpoint }) => { return useMutation({ mutationKey: [key], mutationFn: async (data = null) => { return await Post({ endpoint, data }); } }); }; var Query = ({ key, endpoint, data }) => { return useQuery({ queryKey: [key], queryFn: async () => { const _data = data ?? null; return await Post({ endpoint, data: _data }); } }); }; // src/NextQueryClient.ts import { QueryClient, useQueryClient } from "@tanstack/react-query"; var NextQueryClient = QueryClient; var useNextQueryClient = useQueryClient; // src/NextQueryClientProvider.ts import { QueryClientProvider } from "@tanstack/react-query"; var NextQueryClientProvider = QueryClientProvider; // src/zustand.ts import { create as _ } from "zustand"; var create = _; // src/lodash.ts import _2 from "lodash"; var useLodash = _2; // src/moment.ts import moment from "moment"; var useMoment = moment; // src/Api.ts var usePost = Post; var useGet = Get; export { Mutate, NextQueryClient, NextQueryClientProvider, Query, create, useGet, useLodash, useMoment, useNextQueryClient, usePost };