Skip to content

Commit fac0fbc

Browse files
committed
feat: implement useServerFile hook for file upload and deletion functionality
1 parent d8cb119 commit fac0fbc

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

src/hooks/use-file-upload.tsx

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
// import { DIRECTORY_NAME } from "@/backend/domain-models";
2+
import { useState } from "react";
3+
4+
export const useServerFile = () => {
5+
// loading states
6+
const [uploading, setUploading] = useState<boolean>(false);
7+
const [deleting, setDeleting] = useState<boolean>(false);
8+
9+
const uploadFile = async (param: {
10+
files: FileList | File[];
11+
// directory: DIRECTORY_NAME;
12+
generateUniqueFileName?: boolean;
13+
}) => {
14+
// loader
15+
setUploading(true);
16+
17+
// post files to server
18+
// const keys = Array.from(param.files).map((file) => {
19+
// return param.generateUniqueFileName
20+
// ? `${param.directory}/${generateRandomString(30, "counterbd-")}-${
21+
// file.name
22+
// }`
23+
// : `${param.directory}/${file.name}`;
24+
// });
25+
26+
const signApi = await fetch(`/api/storage/sign`, {
27+
method: "POST",
28+
// body: JSON.stringify({ keys }),
29+
});
30+
const signResponse = await signApi.json();
31+
32+
const putResponses = await Promise.all(
33+
signResponse.data.signedUrls.map((signedUrl: string, index: number) =>
34+
fetch(signedUrl, {
35+
method: "PUT",
36+
body: param.files[index],
37+
headers: {
38+
"Content-Type": "multipart/form-data",
39+
},
40+
})
41+
)
42+
);
43+
44+
setUploading(false);
45+
46+
if (!putResponses) {
47+
return {
48+
success: false,
49+
error: "Failed to upload file",
50+
data: null,
51+
};
52+
}
53+
54+
return {
55+
success: true,
56+
error: null,
57+
// data: { keys },
58+
};
59+
};
60+
61+
// delete files from server
62+
const deleteFile = async (keys: string[]) => {
63+
setDeleting(true);
64+
65+
fetch(`/api/storage/delete`, {
66+
method: "POST",
67+
body: JSON.stringify({ keys }),
68+
}).then(() => {
69+
setDeleting(false);
70+
});
71+
};
72+
73+
return {
74+
uploadFile,
75+
uploading,
76+
deleting,
77+
deleteFile,
78+
};
79+
};

0 commit comments

Comments
 (0)