Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
26 changes: 9 additions & 17 deletions src/app/api/announcements/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,20 @@ async function handleRequest(fn: () => Promise<NextResponse | undefined>) {
} catch (error) {
console.error("서버 오류:", error);
const msg =
error instanceof Error ? error.message : "서버 오류가 발생했습니다.";
error instanceof Error
? error.message
: typeof error === "object" &&
error !== null &&
"message" in error &&
typeof (error as { message?: unknown }).message === "string"
? String((error as { message: string }).message)
: "서버 오류가 발생했습니다.";
return NextResponse.json({ error: msg }, { status: 500 });
}
}

// ------------------------------------------------------
// 권한 체크
// 1) 세션이 없거나, user가 없으면 -> 로그인 필요 반환
// 3) 세션에 user.email이 없을 경우 -> 관리자 권한 필요 반환

// 251121. 테스트를 위해 임시방편으로 NEXT_PUBLIC_ADMIN_EMAILS로
// 이메일을 받고 있는데, 추후 session?.user?.role === "admin"로 원복 필요
// ------------------------------------------------------

export async function checkAdminFnc() {
Expand All @@ -40,10 +42,6 @@ export async function checkAdminFnc() {
};
}

// const adminEmails =
// process.env.NEXT_PUBLIC_ADMIN_EMAILS?.split(",").map((e) => e.trim()) || [];

// 관리자 권한 체크 (오류코드 403)
const isAdmin = authUser.role === "admin";
if (!isAdmin) {
return {
Expand All @@ -55,13 +53,7 @@ export async function checkAdminFnc() {
};
}


//------------------ 디버깅용
const user_id = authUser.userId ?? crypto.randomUUID();
if (!authUser.userId) {
console.warn("세션에 user_id가 없습니다. 임시 UUID를 사용합니다.");
}
//------------------ END 디버깅용
const user_id = authUser.userId;

return { authorized: true, user_id };
}
Expand Down
26 changes: 20 additions & 6 deletions src/lib/api/notices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,29 @@ export const ITEM_PER_PAGE = NOTICE_CONSTANS.ITEMS_PER_PAGE;
// ------------------------------------------------------

async function handleApiResponse<T>(response: Response): Promise<T> {
// HTTP 응답 상태 확인
const errorData = await response.json().catch(() => ({}));

if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error || `API 요청 실패: ${response.status}`);
const serverMessage =
typeof errorData?.error === "string" ? errorData.error : null;

const fallbackMessageByStatus: Record<number, string> = {
400: "잘못된 요청입니다.",
401: "로그인이 필요합니다.",
403: "권한이 없습니다.",
404: "요청한 데이터를 찾을 수 없습니다.",
500: "서버 오류가 발생했습니다.",
};

const fallback =
fallbackMessageByStatus[response.status] ||
`API 요청 실패: ${response.status}`;

throw new Error(serverMessage || fallback);
}
return response.json();
}

return errorData as T;
}
// ------------------------------------------------------
// 공지사항 목록 조회
// ------------------------------------------------------
Expand All @@ -28,7 +43,6 @@ export async function getNotices(
try {
const response = await fetch(
`/api/announcements?page=${page}&limit=${limit}`
// /api/announcements?page=1&limit=8
);
const result = await handleApiResponse<{
data: Notice[];
Expand Down
Loading