Themes modal udpated

This commit is contained in:
Sean Edmunds
2024-08-15 17:07:48 -05:00
parent a47f201fff
commit a37ab84f65
45 changed files with 1480 additions and 1177 deletions

View File

@@ -1,21 +1,25 @@
import { useQuery, useQueryClient, useMutation, useInfiniteQuery } from '@tanstack/react-query';
import { useCallback } from 'react';
import { toast } from 'react-toastify';
import {
useQuery,
useQueryClient,
useMutation,
useInfiniteQuery,
} 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",
},
};
@@ -27,30 +31,28 @@ export function useQueryAPI({ endpoint }: { endpoint: string }) {
};
return useQuery({
queryKey: ['GET', endpoint],
queryKey: ["GET", endpoint],
queryFn: () => callEndpoint(endpoint),
});
}
export function useMutationAPI() {
const callEndpoint = async (
method: string,
endpoint: string,
body: object | undefined | null,
) => {
const url = `http://localhost:5000/trigger/${endpoint}`;
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),
};
@@ -58,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,
@@ -71,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,
@@ -108,16 +110,18 @@ 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];
queryClient.invalidateQueries({ queryKey: ['GET', `/${GetEndpoint}`] });
const GetEndpoint = variables.endpoint.split("/")[1];
queryClient.invalidateQueries({
queryKey: ["GET", `/${GetEndpoint}`],
});
}
}
},
@@ -125,32 +129,30 @@ export function useMutationAPI() {
}
export function useFileUploadAPI() {
const callEndpoint = async (
method: string,
endpoint: string,
body?: object | FormData | undefined | null,
) => {
const url = `http://localhost:5000/trigger/${endpoint}`;
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,
@@ -190,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}`] });
}
},
});
@@ -204,12 +206,11 @@ export function useFetchAllRecordsAPI({ endpoint }: { endpoint: string }) {
const queryClient = useQueryClient();
const fetchPage = async (page: number, retryCount = 0): Promise<any> => {
// Start building the URL
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);
@@ -217,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",
},
};
@@ -294,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,
@@ -322,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,
@@ -354,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;
@@ -368,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,
@@ -391,7 +392,6 @@ export function useDownloadFile() {
return downloadFile;
}
export const useFetchInfiniteQuery = ({
endpoint,
pageSize = 10,
@@ -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,12 +431,25 @@ export const useFetchInfiniteQuery = ({
}
return allPages.length + 1;
};
const { data, isLoading, isFetchingNextPage, fetchNextPage, isError, isFetching } =
useInfiniteQuery({
queryKey,
queryFn,
getNextPageParam,
initialPageParam: 1,
});
return { data, isLoading, isFetchingNextPage, fetchNextPage, isError, isFetching };
};
const {
data,
isLoading,
isFetchingNextPage,
fetchNextPage,
isError,
isFetching,
} = useInfiniteQuery({
queryKey,
queryFn,
getNextPageParam,
initialPageParam: 1,
});
return {
data,
isLoading,
isFetchingNextPage,
fetchNextPage,
isError,
isFetching,
};
};