Files
frontend/apps/sn/app/components/lib/utils/fileDeleteUtil.tsx
T

124 lines
3.9 KiB
TypeScript

/**
* 📄 File Delete Utility
* 파일 삭제 유틸리티
*
* - 첨부 파일 삭제 기능 (단일 파일 지원)
* - 쿠키 기반 인증 토큰 관리 및 사용자 조회
* - Axios 기반 HTTP 요청 처리
* - 타입 안전성 보장을 위한 인터페이스 활용
* - 에러 핸들링 및 응답 처리 표준화
* - 파일 삭제 진행 상태 콜백 지원
*
* 🔗 사용 API
* - 첨부파일 삭제및 Soft Delete 삭제(첨부파일코드로 삭제): DELETE /api/v1/atfl/attachments/atflCd/{atflCd} (attach-service)
*/
import { getCookie } from "@/shared/lib";
import { SITE_ID } from "@/shared/config";
import { ENDPOINT } from "../api/attachment/attachment-service";
const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id";
const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization";
type DeleteOptions = {
handleDeleteStart?: () => void;
handleDeleteSuccess?: (response: Response) => void;
handleDeleteError?: (error: Error) => void;
};
export const handleDelete = async (
atflCd: string,
options?: DeleteOptions
): Promise<void> => {
if (!atflCd) {
const error = new Error("첨부파일 코드가 필요합니다.");
options?.handleDeleteError?.(error);
throw error;
}
try {
options?.handleDeleteStart?.();
const response = await fetch(
`${ENDPOINT.ATTACH_SERVICE.DELETE_FILE_BY_ATFLCD}/${atflCd}`,
{
method: "DELETE",
headers: {
"Content-Type": "application/json",
"X-Site-Id": SITE_ID,
[CLAIM_NAME]: getCookie(CLAIM_NAME) ?? "",
[AUTH_USER_ID]: getCookie(AUTH_USER_ID) ?? "",
},
}
);
if (!response.ok) {
throw new Error(`파일 삭제 실패: ${response.status} ${response.statusText}`);
}
options?.handleDeleteSuccess?.(response);
} catch (error) {
const deleteError = error instanceof Error
? error
: new Error("파일 삭제 중 알 수 없는 오류가 발생했습니다.");
console.error("파일 삭제 오류:", deleteError);
options?.handleDeleteError?.(deleteError);
throw deleteError;
}
};
// 여러 파일을 삭제하는 함수
// export const handleMultipleDelete = async (
// atflCds: string[],
// options?: DeleteOptions & {
// handleProgress?: (completed: number, total: number) => void;
// }
// ): Promise<void> => {
// if (!atflCds || atflCds.length === 0) {
// const error = new Error("삭제할 파일이 없습니다.");
// options?.handleDeleteError?.(error);
// throw error;
// }
// try {
// options?.handleDeleteStart?.();
// const deletePromises = atflCds.map(async (atflCd, index) => {
// try {
// await handleDelete(atflCd);
// options?.handleProgress?.(index + 1, atflCds.length);
// return { success: true, atflCd };
// } catch (error) {
// return { success: false, atflCd, error };
// }
// });
// const results = await Promise.allSettled(deletePromises);
// const failedDeletes = results
// .filter((result): result is PromiseFulfilledResult<{ success: false; atflCd: string; error: any }> =>
// result.status === 'fulfilled' && !result.value.success
// )
// .map(result => result.value);
// if (failedDeletes.length > 0) {
// const error = new Error(
// `일부 파일 삭제 실패: ${failedDeletes.map(f => f.atflCd).join(', ')}`
// );
// options?.handleDeleteError?.(error);
// throw error;
// }
// options?.handleDeleteSuccess?.(new Response());
// } catch (error) {
// const deleteError = error instanceof Error
// ? error
// : new Error("파일 삭제 중 알 수 없는 오류가 발생했습니다.");
// console.error("파일 삭제 오류:", deleteError);
// options?.handleDeleteError?.(deleteError);
// throw deleteError;
// }
// };