feat: Refactor Upload Folders to Use Mutations for HTTP Request Management (#2810)

* ✨ (frontend): Add new API queries for user authentication and messages handling
📝 (frontend): Update API queries for user authentication to include new functionalities like logout, reset password, update user, add user, login user, and refresh access token
📝 (frontend): Update API queries for messages to change the update messages functionality to use PUT method instead of PATCH

* ✨ (sideBarFolderButtons/index.tsx): Add usePostUploadFolders query to handle uploading folders and files
🔧 (constants.ts): Add FOLDERS constant to API URLs for folder-related endpoints
🔧 (folders/index.tsx): Add use-post-upload-folders query to handle uploading folders and files

🔧 (use-update-messages.ts): Remove unused file use-update-messages.ts to clean up the project
🔧 (foldersStore.tsx): Remove unused uploadFolder function to improve code maintainability and reduce complexity
🔧 (folders/index.ts): Remove unused uploadFolder function to simplify the codebase and improve readability

* [autofix.ci] apply automated fixes

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
This commit is contained in:
Cristhian Zanforlin Lousa 2024-07-23 09:16:42 -03:00 • committed by GitHub
commit 65acbd50a3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 86 additions and 60 deletions

View file

@ -1,3 +1,4 @@
import { usePostUploadFolders } from "@/controllers/API/queries/folders";
import { useEffect, useRef, useState } from "react";
import { useLocation } from "react-router-dom";
import { FolderType } from "../../../../pages/MainPage/entities";
@ -33,7 +34,6 @@ const SideBarFoldersButtonsComponent = ({
const [editFolders, setEditFolderName] = useState(
folders.map((obj) => ({ name: obj.name, edit: false })),
);
const uploadFolder = useFolderStore((state) => state.uploadFolder);
const currentFolder = pathname.split("/");
const urlWithoutPath = pathname.split("/").length < 4;
const myCollectionId = useFolderStore((state) => state.myCollectionId);
@ -61,21 +61,49 @@ const SideBarFoldersButtonsComponent = ({
handleFolderChange,
);
const { mutate } = usePostUploadFolders();
const handleUploadFlowsToFolder = () => {
uploadFolder(folderId)
.then(() => {
getFolderById(folderId);
setSuccessData({
title: "Uploaded successfully",
const input = document.createElement("input");
input.type = "file";
input.accept = ".json";
input.click();
input.onchange = (event: Event) => {
if (
(event.target as HTMLInputElement).files![0].type === "application/json"
) {
const file = (event.target as HTMLInputElement).files![0];
const formData = new FormData();
formData.append("file", file);
file.text().then(async (text) => {
const data = JSON.parse(text);
if (data.data?.nodes) {
await useFlowsManagerStore.getState().addFlow(true, data);
getFolderById(folderId);
} else {
mutate(
{ formData },
{
onSuccess: () => {
getFolderById(folderId);
setSuccessData({
title: "Uploaded successfully",
});
},
onError: (err) => {
console.log(err);
setErrorData({
title: `Error on upload`,
list: [err["response"]["data"]],
});
},
},
);
}
});
})
.catch((err) => {
console.log(err);
setErrorData({
title: `Error on upload`,
list: [err["response"]["data"]],
});
});
}
};
};
const handleDownloadFolder = (id: string) => {

View file

@ -13,6 +13,7 @@ export const URLs = {
AUTOLOGIN: "auto_login",
REFRESH: "refresh",
BUILD: `build`,
FOLDERS: `folders`,
} as const;
export function getURL(key: keyof typeof URLs, params: any = {}) {

View file

@ -1 +1,10 @@
export * from "./use-delete-users";
export * from "./use-get-autologin";
export * from "./use-get-user";
export * from "./use-get-users-page";
export * from "./use-patch-logout";
export * from "./use-patch-reset-password";
export * from "./use-patch-update-user";
export * from "./use-post-add-user";
export * from "./use-post-login-user";
export * from "./use-post-refresh-access";

View file

@ -0,0 +1,41 @@
import useAuthStore from "@/stores/authStore";
import {
changeUser,
resetPasswordType,
useMutationFunctionType,
} from "@/types/api";
import { UseMutationResult } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { api } from "../../api";
import { getURL } from "../../helpers/constants";
import { UseRequestProcessor } from "../../services/request-processor";
export const useLogout: useMutationFunctionType<undefined, void> = (
options?,
) => {
const { mutate } = UseRequestProcessor();
const navigate = useNavigate();
const logout = useAuthStore((state) => state.logout);
async function logoutUser(): Promise<any> {
const autoLogin = useAuthStore.getState().autoLogin;
if (autoLogin) {
return {};
}
const res = await api.patch(`${getURL("LOGOUT")}`);
return res.data;
}
const mutation = mutate(["useLogout"], logoutUser, {
onSuccess: () => {
logout();
navigate("/login");
},
onError: (error) => {
console.error(error);
},
...options,
});
return mutation;
};

View file

@ -0,0 +1,40 @@
import {
changeUser,
resetPasswordType,
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 resetPasswordParams {
user_id: string;
password: resetPasswordType;
}
export const useResetPassword: useMutationFunctionType<
undefined,
resetPasswordParams
> = (options?) => {
const { mutate } = UseRequestProcessor();
async function resetPassword({
user_id,
password,
}: resetPasswordParams): Promise<any> {
const res = await api.patch(
`${getURL("USERS")}/${user_id}/reset-password`,
password,
);
return res.data;
}
const mutation: UseMutationResult<
resetPasswordParams,
any,
resetPasswordParams
> = mutate(["useResetPassword"], resetPassword, options);
return mutation;
};

View file

@ -0,0 +1,27 @@
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 UpdateUserParams {
user_id: string;
user: changeUser;
}
export const useUpdateUser: useMutationFunctionType<
undefined,
UpdateUserParams
> = (options?) => {
const { mutate } = UseRequestProcessor();
async function updateUser({ user_id, user }: UpdateUserParams): Promise<any> {
const res = await api.patch(`${getURL("USERS")}/${user_id}`, user);
return res.data;
}
const mutation: UseMutationResult<UpdateUserParams, any, UpdateUserParams> =
mutate(["useUpdateUser"], updateUser, options);
return mutation;
};

View file

@ -0,0 +1,30 @@
import { Users, useMutationFunctionType } from "@/types/api";
import { UserInputType } from "@/types/components";
import { UseMutationResult } from "@tanstack/react-query";
import { api } from "../../api";
import { getURL } from "../../helpers/constants";
import { UseRequestProcessor } from "../../services/request-processor";
export const useAddUser: useMutationFunctionType<undefined, UserInputType> = (
options?,
) => {
const { mutate } = UseRequestProcessor();
const addUserFunction = async (
user: UserInputType,
): Promise<Array<Users>> => {
const res = await api.post(`${getURL("USERS")}`, user);
return res.data;
};
const mutation: UseMutationResult<Array<Users>, any, UserInputType> = mutate(
["useAddUser"],
async (payload: UserInputType) => {
const res = await addUserFunction(payload);
return res;
},
options,
);
return mutation;
};

View file

@ -0,0 +1,35 @@
import { LoginType, 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";
export const useLoginUser: useMutationFunctionType<undefined, LoginType> = (
options?,
) => {
const { mutate } = UseRequestProcessor();
async function updateUser({ password, username }: LoginType): Promise<any> {
const res = await api.post(
`${getURL("LOGIN")}`,
new URLSearchParams({
username: username,
password: password,
}).toString(),
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
},
);
return res.data;
}
const mutation: UseMutationResult<LoginType, any, LoginType> = mutate(
["useLoginUser"],
updateUser,
options,
);
return mutation;
};

View file

@ -0,0 +1,24 @@
import { LoginType, 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";
export const useRefreshAccessToken: useMutationFunctionType<undefined, any> = (
options?,
) => {
const { mutate } = UseRequestProcessor();
async function refreshAccess(): Promise<any> {
const res = await api.post(`${getURL("REFRESH")}`);
return res.data;
}
const mutation: UseMutationResult = mutate(
["useRefrshAccessToken"],
refreshAccess,
options,
);
return mutation;
};

View file

@ -0,0 +1 @@
export * from "./use-post-upload-folders";

View file

@ -0,0 +1,32 @@
import useFlowsManagerStore from "@/stores/flowsManagerStore";
import { useFolderStore } from "@/stores/foldersStore";
import { Users, useMutationFunctionType } from "@/types/api";
import { api } from "../../api";
import { getURL } from "../../helpers/constants";
import { UseRequestProcessor } from "../../services/request-processor";
interface IPostAddUploadFolders {
formData: FormData;
}
export const usePostUploadFolders: useMutationFunctionType<
undefined,
IPostAddUploadFolders
> = (options?) => {
const { mutate } = UseRequestProcessor();
const uploadFoldersFn = async (
payload: IPostAddUploadFolders,
): Promise<void> => {
const res = await api.post(
`${getURL("FOLDERS")}/upload/`,
payload.formData,
);
await useFolderStore.getState().getFoldersApi(true);
return res.data;
};
const mutation = mutate(["usePostUploadFolders"], uploadFoldersFn, options);
return mutation;
};

View file

@ -1,3 +1,3 @@
export * from "./use-delete-messages";
export * from "./use-get-messages";
export * from "./use-update-messages";
export * from "./use-put-update-messages";

View file

@ -0,0 +1,33 @@
import { useMutationFunctionType } from "@/types/api";
import { Message } from "@/types/messages";
import { UseMutationResult } from "@tanstack/react-query";
import { api } from "../../api";
import { getURL } from "../../helpers/constants";
import { UseRequestProcessor } from "../../services/request-processor";
interface UpdateMessageParams {
message: Message;
}
export const useUpdateMessage: useMutationFunctionType<
undefined,
UpdateMessageParams
> = (options?) => {
const { mutate } = UseRequestProcessor();
const updateMessageApi = async (data: Message) => {
if (data.files && typeof data.files === "string") {
data.files = JSON.parse(data.files);
}
const result = await api.put(`${getURL("MESSAGES")}/${data.id}`, data);
return result.data;
};
const mutation: UseMutationResult<
UpdateMessageParams,
any,
UpdateMessageParams
> = mutate(["useUpdateMessages"], updateMessageApi, options);
return mutation;
};

View file

@ -133,50 +133,6 @@ export const useFolderStore = create<FoldersStoreType>((set, get) => ({
setFolderDragging: (folder) => set(() => ({ folderDragging: folder })),
folderIdDragging: "",
setFolderIdDragging: (id) => set(() => ({ folderIdDragging: id })),
uploadFolder: () => {
return new Promise<void>((resolve, reject) => {
const input = document.createElement("input");
input.type = "file";
input.accept = ".json";
input.onchange = (event: Event) => {
if (
(event.target as HTMLInputElement).files![0].type ===
"application/json"
) {
const file = (event.target as HTMLInputElement).files![0];
const formData = new FormData();
formData.append("file", file);
file.text().then((text) => {
const data = JSON.parse(text);
if (data.data?.nodes) {
useFlowsManagerStore
.getState()
.addFlow(true, data)
.then(() => {
resolve();
})
.catch((error) => {
reject(error);
});
} else {
uploadFlowsFromFolders(formData)
.then(() => {
get()
.getFoldersApi(true)
.then(() => {
resolve();
});
})
.catch((error) => {
reject(error);
});
}
});
}
};
input.click();
});
},
starterProjectId: "",
setStarterProjectId: (id) => set(() => ({ starterProjectId: id })),
}));

View file

@ -22,7 +22,6 @@ export type FoldersStoreType = {
setFolderUrl: (folderUrl: string) => void;
folderDragging: boolean;
setFolderDragging: (set: boolean) => void;
uploadFolder: (folderId: string) => Promise<void>;
folderIdDragging: string;
setFolderIdDragging: (id: string) => void;
starterProjectId: string;