|
1 | | -import { useMutation } from "@tanstack/react-query"; |
2 | | -import axios from "axios"; |
| 1 | +import { MutationOptions, useMutation } from "@tanstack/react-query"; |
| 2 | +import axios, { AxiosError } from "axios"; |
3 | 3 | import toast from "react-hot-toast"; |
4 | 4 | import fileSaver from "file-saver"; |
5 | 5 |
|
@@ -36,3 +36,52 @@ export const useDownloadData = () => { |
36 | 36 | }, |
37 | 37 | }); |
38 | 38 | }; |
| 39 | + |
| 40 | +/** S3에 이미지 미리보기 링크 생성 */ |
| 41 | +export const usePresignLogoFile = ( |
| 42 | + getFileCallback: (arg: void) => File, |
| 43 | + cleanUp: (arg: void) => void, |
| 44 | + option: MutationOptions<string> |
| 45 | +) => { |
| 46 | + const file = getFileCallback(); |
| 47 | + const presign = async (targetFile: File) => { |
| 48 | + const logo = { |
| 49 | + type: "LOGO_IMAGE", |
| 50 | + file_name: targetFile.name, |
| 51 | + }; |
| 52 | + const { data } = await axios.post<{ |
| 53 | + urls: { |
| 54 | + file_path: string; |
| 55 | + pre_signed_url: string; |
| 56 | + }[]; |
| 57 | + }>(`${import.meta.env.VITE_BASE_URL}/files/pre-signed`, { |
| 58 | + files: [logo], |
| 59 | + }); |
| 60 | + return { data, presignedFile: targetFile }; |
| 61 | + }; |
| 62 | + return useMutation({ |
| 63 | + ...option, |
| 64 | + mutationFn: () => |
| 65 | + presign(file).then(({ data, presignedFile }) => { |
| 66 | + const url = data.urls[0]; |
| 67 | + |
| 68 | + return new Promise<string>(resolve => { |
| 69 | + axios |
| 70 | + .put(url.pre_signed_url, presignedFile) |
| 71 | + .then(() => |
| 72 | + resolve(`${import.meta.env.VITE_FILE_URL}${url.file_path}`) |
| 73 | + ); |
| 74 | + }); |
| 75 | + }), |
| 76 | + onError: (err: AxiosError<AxiosError>) => { |
| 77 | + if (err.response) { |
| 78 | + if (err.response?.data.message === "Invalid Extension File") { |
| 79 | + toast.error("지원하지 않는 형식의 파일입니다."); |
| 80 | + } |
| 81 | + } else { |
| 82 | + toast.error("네트워크 연결을 확인해주세요."); |
| 83 | + } |
| 84 | + cleanUp(); |
| 85 | + }, |
| 86 | + }); |
| 87 | +}; |
0 commit comments