This commit is contained in:
Sean Edmunds
2024-08-20 16:28:46 -05:00
parent 8152d3fe73
commit 7990f164d6
39 changed files with 824 additions and 772 deletions

View File

@@ -1,25 +1,25 @@
import {
useInfiniteQuery,
useMutation,
useQuery,
useQueryClient,
useMutation,
useInfiniteQuery,
} from "@tanstack/react-query";
import { useCallback } from "react";
import { toast } from "react-toastify";
} from '@tanstack/react-query';
import { useCallback } from 'react';
import { toast } from 'react-toastify';
export function useQueryAPI({ endpoint }: { endpoint: string }) {
const callEndpoint = async (endpoint: string) => {
const url = `http://localhost:5000/trigger/${endpoint}`;
const options: object = {
method: "GET",
method: 'GET',
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "POST, GET, OPTIONS",
"Access-Control-Allow-Credentials": true,
"Sec-Fetch-Mode": "no-cors",
"Sec-Fetch-Site": "same-site",
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
'Access-Control-Allow-Credentials': true,
'Sec-Fetch-Mode': 'no-cors',
'Sec-Fetch-Site': 'same-site',
},
};
@@ -31,7 +31,7 @@ export function useQueryAPI({ endpoint }: { endpoint: string }) {
};
return useQuery({
queryKey: ["GET", endpoint],
queryKey: ['GET', endpoint],
queryFn: () => callEndpoint(endpoint),
});
}
@@ -46,13 +46,13 @@ export function useMutationAPI() {
const options: any = {
method: method,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "POST, GET, OPTIONS",
"Access-Control-Allow-Credentials": true,
"Sec-Fetch-Mode": "no-cors",
"Sec-Fetch-Site": "same-site",
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
'Access-Control-Allow-Credentials': true,
'Sec-Fetch-Mode': 'no-cors',
'Sec-Fetch-Site': 'same-site',
},
body: JSON.stringify(body),
};
@@ -60,7 +60,7 @@ export function useMutationAPI() {
const response = await fetch(url, options);
if (!response.ok) {
const responseData = await response.json();
if (typeof responseData.detail !== "string") {
if (typeof responseData.detail !== 'string') {
const errorResponse = JSON.stringify({
status: response.status,
statusText: response.statusText,
@@ -73,7 +73,7 @@ export function useMutationAPI() {
throw new Error(errorResponse);
}
if (typeof responseData.detail === "object") {
if (typeof responseData.detail === 'object') {
const errorResponse = JSON.stringify({
status: response.status,
statusText: response.statusText,
@@ -110,17 +110,17 @@ export function useMutationAPI() {
}) => callEndpoint(method, endpoint, body),
onMutate: () => {},
onSuccess: (data, variables) => {
queryClient.invalidateQueries({ queryKey: ["GET", variables.endpoint] });
queryClient.invalidateQueries({ queryKey: ['GET', variables.endpoint] });
if (variables.endpoint.includes("/")) {
if (variables.endpoint.includes('/')) {
if ((variables.endpoint.match(/\//g) || []).length > 2) {
const GetEndpoint = variables.endpoint.split("/");
const GetEndpoint = variables.endpoint.split('/');
const Endpoint = `${GetEndpoint[1]}/${GetEndpoint[2]}`;
queryClient.invalidateQueries({ queryKey: ["GET", `/${Endpoint}`] });
queryClient.invalidateQueries({ queryKey: ['GET', `/${Endpoint}`] });
} else {
const GetEndpoint = variables.endpoint.split("/")[1];
const GetEndpoint = variables.endpoint.split('/')[1];
queryClient.invalidateQueries({
queryKey: ["GET", `/${GetEndpoint}`],
queryKey: ['GET', `/${GetEndpoint}`],
});
}
}
@@ -139,20 +139,20 @@ export function useFileUploadAPI() {
const options = {
method: method,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "POST, GET, OPTIONS",
"Access-Control-Allow-Credentials": true,
"Sec-Fetch-Mode": "no-cors",
"Sec-Fetch-Site": "same-site",
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
'Access-Control-Allow-Credentials': true,
'Sec-Fetch-Mode': 'no-cors',
'Sec-Fetch-Site': 'same-site',
},
body: body ?? undefined,
};
const response = await fetch(url, options as unknown as Body);
if (!response.ok) {
const responseData = await response.json();
if (typeof responseData.detail !== "string") {
if (typeof responseData.detail !== 'string') {
const errorResponse = JSON.stringify({
status: response.status,
statusText: response.statusText,
@@ -192,10 +192,10 @@ export function useFileUploadAPI() {
}) => callEndpoint(method, endpoint, body),
onMutate: () => {},
onSuccess: (variables) => {
queryClient.invalidateQueries({ queryKey: ["GET", variables.endpoint] });
if (variables.endpoint?.includes("/")) {
const GetEndpoint = variables.endpoint.split("/")[1];
queryClient.invalidateQueries({ queryKey: ["GET", `/${GetEndpoint}`] });
queryClient.invalidateQueries({ queryKey: ['GET', variables.endpoint] });
if (variables.endpoint?.includes('/')) {
const GetEndpoint = variables.endpoint.split('/')[1];
queryClient.invalidateQueries({ queryKey: ['GET', `/${GetEndpoint}`] });
}
},
});
@@ -210,7 +210,7 @@ export function useFetchAllRecordsAPI({ endpoint }: { endpoint: string }) {
const url = new URL(`http://localhost:5000/trigger/${endpoint}`);
// Check and append custom query parameters from the endpoint
const customParams = new URLSearchParams(endpoint.split("?")[1]);
const customParams = new URLSearchParams(endpoint.split('?')[1]);
for (const [key, value] of customParams) {
if (!url.searchParams.has(key)) {
url.searchParams.append(key, value);
@@ -218,19 +218,19 @@ export function useFetchAllRecordsAPI({ endpoint }: { endpoint: string }) {
}
// Add 'page' and 'size' parameters
url.searchParams.set("page", page.toString()); // Use 'set' to ensure uniqueness
url.searchParams.set("size", pageSize.toString());
url.searchParams.set('page', page.toString()); // Use 'set' to ensure uniqueness
url.searchParams.set('size', pageSize.toString());
const options: any = {
method: "GET",
method: 'GET',
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "POST, GET, OPTIONS",
"Access-Control-Allow-Credentials": true,
"Sec-Fetch-Mode": "no-cors",
"Sec-Fetch-Site": "same-site",
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
'Access-Control-Allow-Credentials': true,
'Sec-Fetch-Mode': 'no-cors',
'Sec-Fetch-Site': 'same-site',
},
};
@@ -295,18 +295,18 @@ export function useFetchAllRecordsAPI({ endpoint }: { endpoint: string }) {
return allItems;
} catch (error) {
// Handling errors in fetching the first page
console.error("Error fetching the first page:", error);
console.error('Error fetching the first page:', error);
return []; // Return empty array on error
}
};
const invalidate = useCallback(() => {
queryClient.invalidateQueries({ queryKey: ["GET", endpoint] });
queryClient.invalidateQueries({ queryKey: ['GET', endpoint] });
}, [queryClient, endpoint]);
return {
...useQuery({
queryKey: ["GET", endpoint],
queryKey: ['GET', endpoint],
queryFn: callEndpoint,
}),
invalidate,
@@ -323,31 +323,31 @@ export function useDownloadFile() {
async ({ endpoint, file_name }: DownloadFileOptions) => {
const url = `http://localhost:5000/trigger/${endpoint}`;
const options: any = {
method: "GET",
method: 'GET',
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "POST, GET, OPTIONS",
"Access-Control-Allow-Credentials": true,
"Sec-Fetch-Mode": "no-cors",
"Sec-Fetch-Site": "same-site",
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
'Access-Control-Allow-Credentials': true,
'Sec-Fetch-Mode': 'no-cors',
'Sec-Fetch-Site': 'same-site',
},
};
const toastID = toast.loading("Processing...");
const toastID = toast.loading('Processing...');
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error("Network response was not ok");
throw new Error('Network response was not ok');
}
const blob = await response.blob();
if (blob.type === "application/json") {
if (blob.type === 'application/json') {
const blob_text = await blob.text();
const cleaned_text = blob_text.replace(/"/g, "");
const cleaned_text = blob_text.replace(/"/g, '');
toast.update(toastID, {
render: cleaned_text,
type: "info",
type: 'info',
isLoading: false,
autoClose: 5000,
closeButton: null,
@@ -355,11 +355,11 @@ export function useDownloadFile() {
return;
}
if (typeof window !== "undefined") {
if (typeof window !== 'undefined') {
const blobURL = window.URL.createObjectURL(blob);
const a = document.createElement("a");
const a = document.createElement('a');
a.style.display = "none";
a.style.display = 'none';
a.href = blobURL;
a.download = file_name;
@@ -369,17 +369,17 @@ export function useDownloadFile() {
document.body.removeChild(a);
toast.update(toastID, {
render: `${file_name} Downloaded`,
type: "success",
type: 'success',
isLoading: false,
autoClose: 5000,
closeButton: null,
});
}
} catch (error) {
console.error("Download failed:", error);
console.error('Download failed:', error);
toast.update(toastID, {
render: `Error Downloading ${file_name}. Please try again.`,
type: "error",
type: 'error',
isLoading: false,
autoClose: 5000,
closeButton: null,
@@ -399,27 +399,27 @@ export const useFetchInfiniteQuery = ({
endpoint: string;
pageSize?: number;
}) => {
const queryKey = ["GET", endpoint];
const queryKey = ['GET', endpoint];
const fetchInfiniteQuery = async (endpoint: string) => {
const url = `http://localhost:5000/trigger/${endpoint}`;
const requestOptions: any = {
method: "GET",
method: 'GET',
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "POST, GET, OPTIONS",
"Access-Control-Allow-Credentials": true,
"Sec-Fetch-Mode": "no-cors",
"Sec-Fetch-Site": "same-site",
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
'Access-Control-Allow-Credentials': true,
'Sec-Fetch-Mode': 'no-cors',
'Sec-Fetch-Site': 'same-site',
},
};
try {
const response = await fetch(url, requestOptions);
return await response.json();
} catch (error) {
console.error("Error fetching transactions:", error);
console.error('Error fetching transactions:', error);
throw error;
}
};
@@ -431,19 +431,13 @@ export const useFetchInfiniteQuery = ({
}
return allPages.length + 1;
};
const {
data,
isLoading,
isFetchingNextPage,
fetchNextPage,
isError,
isFetching,
} = useInfiniteQuery({
queryKey,
queryFn,
getNextPageParam,
initialPageParam: 1,
});
const { data, isLoading, isFetchingNextPage, fetchNextPage, isError, isFetching } =
useInfiniteQuery({
queryKey,
queryFn,
getNextPageParam,
initialPageParam: 1,
});
return {
data,
isLoading,