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 new use-query endpoint of upload files #2533

Merged
merged 17 commits into from
Jul 4, 2024
Merged
Show file tree
Hide file tree
Changes from 9 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
39 changes: 21 additions & 18 deletions src/frontend/src/components/inputFileComponent/index.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { usePostUploadFile } from "@/controllers/API/queries/files/use-post-upload-file";
import { useEffect, useState } from "react";
import {
CONSOLE_ERROR_MSG,
Expand Down Expand Up @@ -46,6 +47,25 @@ export default function InputFileComponent({
setMyValue(value);
}, [value]);

const mutation = usePostUploadFile({
callbackSuccess: (data, file) => {
// Get the file name from the response
const { file_path } = data;

// sets the value that goes to the backend
onFileChange(file_path);
// Update the state and callback with the name of the file
// sets the value to the user
setMyValue(file.name);
onChange(file.name);
setLoading(false);
},
callbackError: () => {
console.error(CONSOLE_ERROR_MSG);
setLoading(false);
},
});

const handleButtonClick = (): void => {
// Create a file input element
const input = document.createElement("input");
Expand All @@ -63,24 +83,7 @@ export default function InputFileComponent({
// Check if the file type is correct
if (file && checkFileType(file.name)) {
// Upload the file
uploadFile(file, currentFlowId)
.then((res) => res.data)
.then((data) => {
// Get the file name from the response
const { file_path } = data;

// sets the value that goes to the backend
onFileChange(file_path);
// Update the state and callback with the name of the file
// sets the value to the user
setMyValue(file.name);
onChange(file.name);
setLoading(false);
})
.catch(() => {
console.error(CONSOLE_ERROR_MSG);
setLoading(false);
});
mutation.mutate({ file, id: currentFlowId });
} else {
// Show an error if the file type is not allowed
setErrorData({
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 @@ -3,6 +3,7 @@ import { BASE_URL_API } from "../../../constants/constants";
export const URLs = {
TRANSACTIONS: `monitor/transactions`,
API_KEY: `api_key`,
FILES: `files`,
VERSION: `version`,
} as const;

Expand Down
2 changes: 2 additions & 0 deletions src/frontend/src/controllers/API/queries/files/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./use-get-download-images";
export * from "./use-get-profile-pictures";
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { keepPreviousData } from "@tanstack/react-query";
import { useQueryFunctionType } from "../../../../types/api";
import { api } from "../../api";
import { getURL } from "../../helpers/constants";
import { UseRequestProcessor } from "../../services/request-processor";

interface DownloadImagesQueryParams {
flowId: string;
fileName: string;
}

export interface DownloadImagesResponse {
response: string;
}

export const useGetDownloadImagesQuery: useQueryFunctionType<
DownloadImagesQueryParams,
DownloadImagesResponse
> = ({ flowId, fileName }) => {
const { query } = UseRequestProcessor();

const getDownloadImagesFn = async ({
flowId,
fileName,
}: {
flowId: string;
fileName: string;
}) => {
return await api.get<DownloadImagesResponse>(
`${getURL("FILES")}/images/${flowId}/${fileName}`,
);
};

const queryResult = query(
["useGetDownloadImagesQuery"],
async () => {
const response = await getDownloadImagesFn({
flowId,
fileName,
});
return response["data"];
},
{
placeholderData: keepPreviousData,
},
);

return queryResult;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { keepPreviousData } from "@tanstack/react-query";
import { useQueryFunctionType } from "../../../../types/api";
import { api } from "../../api";
import { getURL } from "../../helpers/constants";
import { UseRequestProcessor } from "../../services/request-processor";

interface ProfilePicturesQueryParams {}

export interface ProfilePicturesResponse {
files: string[];
}

export const useGetProfilePicturesQuery: useQueryFunctionType<
ProfilePicturesQueryParams,
ProfilePicturesResponse
> = () => {
const { query } = UseRequestProcessor();

const getProfilePicturesFn = async () => {
return await api.get<ProfilePicturesResponse>(
`${getURL("FILES")}/profile_pictures/list`,
);
};

const queryResult = query(
["useGetProfilePicturesQuery"],
async () => {
const response = await getProfilePicturesFn();
return response["data"];
},
{
placeholderData: keepPreviousData,
},
);

return queryResult;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
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 IPostUploadFile {
file: File;
id: string;
}

export const usePostUploadFile: useMutationFunctionType<IPostUploadFile> = ({
callbackSuccess,
callbackError,
}) => {
const { mutate } = UseRequestProcessor();

const postUploadFileFn = async (payload: IPostUploadFile): Promise<any> => {
const formData = new FormData();
formData.append("file", payload.file);

const response = await api.post<any>(
`${getURL("FILES")}/upload/${payload.id}`,
formData,
);

return { data: response.data, file: payload.file };
};

const mutation: UseMutationResult<any, any, IPostUploadFile> = mutate(
["usePostUploadFile"],
async (payload: IPostUploadFile) => {
const res = await postUploadFileFn(payload);
return res;
},
{
onError: (err) => {
if (callbackError) {
callbackError(err);
}
},
onSuccess: (data) => {
if (callbackSuccess) {
callbackSuccess(data.data, data.file);
}
},
},
);

return mutation;
};
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Button } from "../../../../../../components/ui/button";

import { usePostUploadFile } from "@/controllers/API/queries/files/use-post-upload-file";
import { useEffect, useState } from "react";
import IconComponent from "../../../../../../components/genericIconComponent";
import { BASE_URL_API } from "../../../../../../constants/constants";
Expand Down Expand Up @@ -66,6 +67,16 @@ export default function IOFileInput({ field, updateValue }: IOFileInputProps) {
setIsDragging(false);
};

const mutation = usePostUploadFile({
callbackSuccess: (data) => {
const { file_path } = data;
setFilePath(file_path);
},
callbackError: () => {
console.error("Error occurred while uploading file");
},
});

const upload = async (file) => {
if (file) {
// Check if a file was selected
Expand All @@ -80,17 +91,7 @@ export default function IOFileInput({ field, updateValue }: IOFileInputProps) {
document.body.appendChild(imgElement); // Add the image to the body or replace this with your desired location
};
fileReader.readAsDataURL(file);

uploadFile(file, currentFlowId)
.then((res) => res.data)
.then((data) => {
// Get the file name from the response
const { file_path, flowId } = data;
setFilePath(file_path);
})
.catch(() => {
console.error("Error occurred while uploading file");
});
mutation.mutate({ file, id: currentFlowId });
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
FS_ERROR_TEXT,
SN_ERROR_TEXT,
} from "../../../../../../constants/constants";
import useFileUpload from "./use-file-upload";
// import useFileUpload from "./use-file-upload";

const useDragAndDrop = (
setIsDragging: (value: boolean) => void,
Expand All @@ -31,48 +31,11 @@ const useDragAndDrop = (
setIsDragging(false);
};

const onDrop = (e) => {
e.preventDefault();
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
handleFiles(e.dataTransfer.files, setFiles, currentFlowId, setErrorData);
e.dataTransfer.clearData();
}
setIsDragging(false);
};
return {
dragOver,
dragEnter,
dragLeave,
onDrop,
};
};

const handleFiles = (files, setFiles, currentFlowId, setErrorData) => {
if (files) {
const file = files?.[0];
const fileExtension = file.name.split(".").pop()?.toLowerCase();
if (
!fileExtension ||
!ALLOWED_IMAGE_INPUT_EXTENSIONS.includes(fileExtension)
) {
console.log("Error uploading file");
setErrorData({
title: "Error uploading file",
list: [FS_ERROR_TEXT, SN_ERROR_TEXT],
});
return;
}
const uid = new ShortUniqueId();
const id = uid.randomUUID(3);
const type = files[0].type.split("/")[0];
const blob = files[0];

setFiles((prevFiles) => [
...prevFiles,
{ file: blob, loading: true, error: false, id, type },
]);

useFileUpload(blob, currentFlowId, setFiles, id);
}
};
export default useDragAndDrop;

This file was deleted.

This file was deleted.

Loading
Loading