Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: add useQuery management on globalVariables CRUD #3121

Merged
merged 4 commits into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
import { AuthContext } from "./contexts/authContext";
import { autoLogin } from "./controllers/API";
import { useGetHealthQuery } from "./controllers/API/queries/health";
import { useGetGlobalVariables } from "./controllers/API/queries/variables";
import { useGetVersionQuery } from "./controllers/API/queries/version";
import { setupAxiosDefaults } from "./controllers/API/utils";
import useTrackLastVisitedPath from "./hooks/use-track-last-visited-path";
Expand All @@ -42,6 +43,8 @@ export default function App() {

const isLoadingFolders = useFolderStore((state) => state.isLoadingFolders);

const { mutate: mutateGetGlobalVariables } = useGetGlobalVariables();

const {
data: healthData,
isFetching: fetchingHealth,
Expand All @@ -66,6 +69,7 @@ export default function App() {
if (user && user["access_token"]) {
user["refresh_token"] = "auto";
login(user["access_token"], "auto");
mutateGetGlobalVariables();
setUserData(user);
setAutoLogin(true);
fetchAllData();
Expand Down Expand Up @@ -99,6 +103,7 @@ export default function App() {
*/
return () => abortController.abort();
}, []);

const fetchAllData = async () => {
setTimeout(async () => {
await Promise.all([refreshStars(), fetchData()]);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { usePostGlobalVariables } from "@/controllers/API/queries/variables";
import { useState } from "react";
import { registerGlobalVariable } from "../../controllers/API";
import BaseModal from "../../modals/baseModal";
import useAlertStore from "../../stores/alertStore";
import { useGlobalVariablesStore } from "../../stores/globalVariablesStore/globalVariables";
Expand Down Expand Up @@ -28,6 +28,7 @@ export default function AddNewVariableButton({
const [open, setOpen] = useState(false);
const setErrorData = useAlertStore((state) => state.setErrorData);
const componentFields = useTypesStore((state) => state.ComponentFields);

const unavaliableFields = new Set(
Object.keys(
useGlobalVariablesStore((state) => state.unavaliableFields) ?? {},
Expand All @@ -46,6 +47,9 @@ export default function AddNewVariableButton({
(state) => state.addGlobalVariable,
);

const { mutate: mutateAddGlobalVariable } = usePostGlobalVariables();
const setSuccessData = useAlertStore((state) => state.setSuccessData);

function handleSaveVariable() {
let data: {
name: string;
Expand All @@ -58,17 +62,22 @@ export default function AddNewVariableButton({
value,
default_fields: fields,
};
registerGlobalVariable(data)
.then((res) => {

mutateAddGlobalVariable(data, {
onSuccess: (res) => {
const { name, id, type } = res.data;
addGlobalVariable(name, id, type, fields);
setKey("");
setValue("");
setType("");
setFields([]);
setOpen(false);
})
.catch((error) => {

setSuccessData({
title: `Variable ${name} created successfully`,
});
},
onError: (error) => {
let responseError = error as ResponseErrorDetailAPI;
setErrorData({
title: "Error creating variable",
Expand All @@ -77,8 +86,10 @@ export default function AddNewVariableButton({
"An unexpected error occurred while adding a new variable. Please try again.",
],
});
});
},
});
}

return (
<BaseModal
open={open}
Expand Down
35 changes: 20 additions & 15 deletions src/frontend/src/components/inputGlobalComponent/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { useDeleteGlobalVariables } from "@/controllers/API/queries/variables";
import { useEffect } from "react";
import { Controller } from "react-hook-form";
import { deleteGlobalVariable } from "../../controllers/API";
import DeleteConfirmationModal from "../../modals/deleteConfirmationModal";
import useAlertStore from "../../stores/alertStore";
import { useGlobalVariablesStore } from "../../stores/globalVariablesStore/globalVariables";
Expand Down Expand Up @@ -28,6 +27,8 @@ export default function InputGlobalComponent({
);
const setErrorData = useAlertStore((state) => state.setErrorData);

const { mutate: mutateDeleteGlobalVariable } = useDeleteGlobalVariables();

useEffect(() => {
if (data && globalVariablesEntries)
if (data.load_from_db && !globalVariablesEntries.includes(data.value)) {
Expand All @@ -38,19 +39,23 @@ export default function InputGlobalComponent({
async function handleDelete(key: string) {
const id = getVariableId(key);
if (id !== undefined) {
await deleteGlobalVariable(id)
.then(() => {
removeGlobalVariable(key);
if (data?.value === key && data?.load_from_db) {
onChange("", false);
}
})
.catch(() => {
setErrorData({
title: "Error deleting variable",
list: [cn("ID not found for variable: ", key)],
});
});
mutateDeleteGlobalVariable(
{ id },
{
onSuccess: () => {
removeGlobalVariable(key);
if (data?.value === key && data?.load_from_db) {
onChange("", false);
}
},
onError: () => {
setErrorData({
title: "Error deleting variable",
list: [cn("ID not found for variable: ", key)],
});
},
},
);
} else {
setErrorData({
title: "Error deleting variable",
Expand Down
14 changes: 3 additions & 11 deletions src/frontend/src/contexts/authContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,9 @@ import useFlowsManagerStore from "@/stores/flowsManagerStore";
import { createContext, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import Cookies from "universal-cookie";
import {
getGlobalVariables,
getLoggedUser,
requestLogout,
} from "../controllers/API";
import { getLoggedUser, requestLogout } from "../controllers/API";
import useAlertStore from "../stores/alertStore";
import { useFolderStore } from "../stores/foldersStore";
import { useGlobalVariablesStore } from "../stores/globalVariablesStore/globalVariables";
import { useStoreStore } from "../stores/storeStore";
import { Users } from "../types/api";
import { AuthContextType } from "../types/contexts/auth";
Expand Down Expand Up @@ -48,9 +43,7 @@ export function AuthProvider({ children }): React.ReactElement {
);

const getFoldersApi = useFolderStore((state) => state.getFoldersApi);
const setGlobalVariables = useGlobalVariablesStore(
(state) => state.setGlobalVariables,
);

const checkHasStore = useStoreStore((state) => state.checkHasStore);
const fetchApiData = useStoreStore((state) => state.fetchApiData);
const setAllFlows = useFlowsManagerStore((state) => state.setAllFlows);
Expand All @@ -77,8 +70,7 @@ export function AuthProvider({ children }): React.ReactElement {
const isSuperUser = user!.is_superuser;
useAuthStore.getState().setIsAdmin(isSuperUser);
getFoldersApi(true, true);
const res = await getGlobalVariables();
setGlobalVariables(res);

checkHasStore();
fetchApiData();
})
Expand Down
1 change: 1 addition & 0 deletions src/frontend/src/controllers/API/helpers/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export const URLs = {
CUSTOM_COMPONENT: `custom_component`,
FLOWS: `flows`,
FOLDERS: `folders`,
VARIABLES: `variables`,
} as const;

export function getURL(key: keyof typeof URLs, params: any = {}) {
Expand Down
47 changes: 0 additions & 47 deletions src/frontend/src/controllers/API/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -818,53 +818,6 @@ export async function requestLogout() {
}
}

export async function getGlobalVariables(): Promise<{
[key: string]: { id: string; type: string; default_fields: string[] };
}> {
const globalVariables = {};
(await api.get(`${BASE_URL_API}variables/`))?.data?.forEach((element) => {
globalVariables[element.name] = {
id: element.id,
type: element.type,
default_fields: element.default_fields,
};
});
return globalVariables;
}

export async function registerGlobalVariable({
name,
value,
type,
default_fields = [],
}: {
name: string;
value: string;
type?: string;
default_fields?: string[];
}): Promise<AxiosResponse<{ name: string; id: string; type: string }>> {
try {
const response = await api.post(`${BASE_URL_API}variables/`, {
name,
value,
type,
default_fields: default_fields,
});
return response;
} catch (error) {
throw error;
}
}

export async function deleteGlobalVariable(id: string) {
try {
const response = await api.delete(`${BASE_URL_API}variables/${id}`);
return response;
} catch (error) {
throw error;
}
}

export async function updateGlobalVariable(
name: string,
value: string,
Expand Down
4 changes: 4 additions & 0 deletions src/frontend/src/controllers/API/queries/variables/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export * from "./use-delete-global-variables";
export * from "./use-get-global-variables";
export * from "./use-patch-global-variables";
export * from "./use-post-global-variables";
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { useMutationFunctionType } from "@/types/api";
import { UseMutationResult } from "@tanstack/react-query";
import { api } from "../../api";
import { getURL } from "../../helpers/constants";
import { UseRequestProcessor } from "../../services/request-processor";

interface DeleteGlobalVariablesParams {
id: string | undefined;
}

export const useDeleteGlobalVariables: useMutationFunctionType<
undefined,
DeleteGlobalVariablesParams
> = (options?) => {
const { mutate } = UseRequestProcessor();

const deleteGlobalVariables = async ({
id,
}: DeleteGlobalVariablesParams): Promise<any> => {
const res = await api.delete(`${getURL("VARIABLES")}/${id}`);
return res.data;
};

const mutation: UseMutationResult<
DeleteGlobalVariablesParams,
any,
DeleteGlobalVariablesParams
> = mutate(["useDeleteGlobalVariables"], deleteGlobalVariables, options);

return mutation;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { useGlobalVariablesStore } from "@/stores/globalVariablesStore/globalVariables";
import { useMutationFunctionType } from "@/types/api";
import { UseMutationResult } from "@tanstack/react-query";
import { api } from "../../api";
import { getURL } from "../../helpers/constants";
import { UseRequestProcessor } from "../../services/request-processor";

type GlobalVariable = {
id: string;
type: string;
default_fields: string[];
name: string;
};

export const useGetGlobalVariables: useMutationFunctionType<undefined, void> = (
options?,
) => {
const { mutate } = UseRequestProcessor();

const setGlobalVariables = useGlobalVariablesStore(
(state) => state.setGlobalVariables,
);

const getGlobalVariables = async (): Promise<[GlobalVariable]> => {
const res = await api.get(`${getURL("VARIABLES")}/`);
return res.data;
};

const getGlobalVariablesFn = async (): Promise<{
[key: string]: GlobalVariable;
}> => {
const data = await getGlobalVariables();
const globalVariables = {};

data?.forEach((element) => {
globalVariables[element.name] = {
id: element.id,
type: element.type,
default_fields: element.default_fields,
};
});

setGlobalVariables(globalVariables);
return globalVariables;
};

const mutation: UseMutationResult<any, any, any> = mutate(
["useGetGlobalVariables"],
getGlobalVariablesFn,
options,
);

return mutation;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { changeUser, useMutationFunctionType } from "@/types/api";
import { UseMutationResult } from "@tanstack/react-query";
import { api } from "../../api";
import { getURL } from "../../helpers/constants";
import { UseRequestProcessor } from "../../services/request-processor";

interface PatchGlobalVariablesParams {
name: string;
value: string;
id: string;
}

export const usePatchGlobalVariables: useMutationFunctionType<
undefined,
PatchGlobalVariablesParams
> = (options?) => {
const { mutate } = UseRequestProcessor();

async function patchGlobalVariables({
name,
value,
id,
}: PatchGlobalVariablesParams): Promise<any> {
const res = await api.patch(`${getURL("VARIABLES")}/${id}`, {
name,
value,
});
return res.data;
}

const mutation: UseMutationResult<
PatchGlobalVariablesParams,
any,
PatchGlobalVariablesParams
> = mutate(["usePatchGlobalVariables"], patchGlobalVariables, options);

return mutation;
};
Loading