Skip to content

Api(client): DeleteCategory 연결#92

Merged
jjangminii merged 1 commit intodevelopfrom
api/#90/category-delete
Sep 13, 2025
Merged

Api(client): DeleteCategory 연결#92
jjangminii merged 1 commit intodevelopfrom
api/#90/category-delete

Conversation

@jjangminii
Copy link
Collaborator

@jjangminii jjangminii commented Sep 13, 2025

📌 Related Issues

관련된 Issue를 태그해주세요. (e.g. - close #25)

📄 Tasks

  • 사이드바 카테고리 삭제 연결

⭐ PR Point (To Reviewer)

📷 Screenshot

image

Summary by CodeRabbit

  • 신규 기능

    • 사이드바에서 카테고리를 실제로 삭제할 수 있습니다. 삭제 확인 후 서버에 반영되며, 완료 시 대시보드 카테고리 목록이 자동으로 새로고침됩니다.
    • 삭제 실패 시 오류가 기록되어 문제 파악이 용이합니다.
  • 리팩터링

    • 삭제 동작을 위한 내부 흐름을 정리하고 훅을 도입해 재사용성을 개선했습니다.
  • 스타일

    • 코드 포맷과 일관성을 개선해 가독성을 향상했습니다.

@jjangminii jjangminii self-assigned this Sep 13, 2025
@jjangminii jjangminii linked an issue Sep 13, 2025 that may be closed by this pull request
@coderabbitai
Copy link

coderabbitai bot commented Sep 13, 2025

Walkthrough

카테고리 삭제 기능을 추가했다. API 레이어에 DELETE 요청 함수를 도입하고, React Query mutation 훅을 추가했으며, Sidebar에서 삭제 확인 동작을 실제 삭제 호출과 캐시 무효화로 연결했다. 일부 코드 스타일(세미콜론, 공백, 개행)을 정비했다.

Changes

Cohort / File(s) Summary
API layer (axios)
apps/client/src/shared/apis/axios.ts
세미콜론 기반으로 postSignUpRequest 인터페이스 서식 수정; deleteCategory(id:number) DELETE API 추가; 경미한 포매팅 수정 및 EOF 개행 추가
React Query hooks
apps/client/src/shared/apis/queries.ts
deleteCategory를 사용한 useDeleteCategory mutation 훅 신규 추가; 기존 훅 로직 변경 없음
Sidebar UI integration
apps/client/src/shared/components/sidebar/Sidebar.tsx
useDeleteCategory 사용해 삭제 처리 추가, 성공 시 dashboardCategories 쿼리 무효화 및 모달 닫기; PopupPortalonDeleteConfirm 시그니처를 (id:number)=>void로 연계; 오류 로그 추가

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor U as User
  participant S as Sidebar
  participant RQ as useDeleteCategory (React Query)
  participant AX as axios.deleteCategory
  participant API as Server API

  U->>S: 삭제 확인 클릭(id)
  S->>RQ: mutate(id)
  RQ->>AX: deleteCategory(id)
  AX->>API: DELETE /api/v1/categories/{id}
  API-->>AX: 200 OK / Error
  AX-->>RQ: 응답 전달

  alt 성공
    RQ->>S: onSuccess 콜백
    S->>RQ: invalidate "dashboardCategories"
    S->>S: 모달 닫기
  else 실패
    RQ->>S: onError 콜백
    S->>S: 오류 로그 출력
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested labels

api, frontend, 🛠️ Feature

Suggested reviewers

  • constantly-dev
  • jllee000
  • karnelll

Poem

토끼는 휙휙, 카테고리 툭툭🗂️
삭제 버튼 눌러봐, 바람처럼 슉—
훅이 받아 돌리고, 캐시는 싹✨
사이드바는 미소짓고, 모달은 닫↩️
깔끔한 정리, 폴짝! 오늘도 완료 🐇

✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch api/#90/category-delete

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Pre-merge checks

❌ Failed checks (3 warnings)
Check name Status Explanation Resolution
Linked Issues Check ⚠️ Warning 요구사항 검토 결과 이 PR은 [#90]의 핵심 목표인 '카테고리 삭제'를 클라이언트 측에서 deleteCategory API와 useDeleteCategory 훅, 그리고 사이드바 삭제 UI로 구현하여 충족합니다. 반면 [#25]의 Progress 컴포넌트 구현 요구사항은 변경사항에 전혀 포함되어 있지 않으므로 해당 이슈는 이 PR에서 해결되지 않았습니다. 따라서 연결된 모든 이슈를 완전히 충족하지 못해 연결 이슈 준수 관점에서는 불합격입니다. 해결 방법으로는 PR에 실제로 해결되는 이슈만 남기고(예: close #90), [#25]가 잘못 연결된 것이라면 링크를 제거해 주세요. 만약 [#25]도 함께 처리할 의도라면 Progress 컴포넌트 관련 커밋과 구현을 이 PR에 포함하거나 이슈를 분리해 주세요. 원하시면 연결 이슈 정리나 PR 분리 방법을 제안해 드리겠습니다.
Out of Scope Changes Check ⚠️ Warning 대체로 변경사항은 카테고리 삭제 연동에 집중되어 있으나 몇 가지 범위를 벗어난 수정이 발견됩니다. apps/client/src/shared/apis/axios.ts의 postSignUpRequest 인터페이스 문법(쉼표→세미콜론) 변경은 기능과 무관한 포맷 수정이며 PopupPortal의 onDeleteConfirm 시그니처 변경은 다른 컴포넌트에 영향을 줄 수 있는 API 변경입니다. 이러한 항목은 의도치 않은 타입 오류나 빌드 실패를 유발할 수 있으므로 '범위 외 변경'으로 간주됩니다. 포맷 변경은 별도의 포맷 전용 커밋으로 분리하거나 되돌리고, PopupPortal 시그니처 변경은 관련 호출부를 모두 함께 수정하거나 변경 내용을 PR 설명에 명확히 기록해 주세요. 또한 CI와 타입체크를 실행해 다른 영향 범위를 확인하고 필요한 경우 테스트를 보완하시기 바랍니다. 원하시면 영향을 받는 호출부 목록과 권장 커밋 분리 방안을 제안하겠습니다.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed 타이틀 "feat: DeleteCategory 연결"은 PR의 핵심 변경사항(카테고리 삭제 API·훅 추가 및 사이드바 삭제 동작 연결)을 간결하게 요약하고 있어 변경 내용과 직접적으로 일치합니다; 불필요한 파일 목록이나 모호한 표현 없이 주요 의도를 전달하므로 동료가 히스토리를 스캔할 때 이해하기 쉽습니다.
Description Check ✅ Passed 현재 PR 설명에는 관련 이슈("close #90")와 작업 요약("사이드바 카테고리 삭제 연결")이 명시되어 있어 템플릿의 핵심 항목이 충족됩니다; PR Point와 Screenshot 섹션은 비어있지만 템플릿상 선택적 항목이므로 설명은 대부분 완성된 것으로 판단됩니다.

@github-actions github-actions bot added the api api 연결 label Sep 13, 2025
@github-actions
Copy link

✅ Storybook chromatic 배포 확인:
🐿️ storybook

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
apps/client/src/shared/apis/axios.ts (1)

42-45: DELETE API 반환 타입/값 일관화 제안

현재 raw AxiosResponse를 그대로 반환합니다. 하위 사용처가 응답 바디를 쓰지 않는다면 void를 반환하도록 단순화해도 됩니다. 선택지:

  • 옵션 A(권장): void 반환
  • 옵션 B: 다른 CRUD와 동일 정책으로 data/data.data만 반환하도록 표준화

예시(옵션 A):

-export const deleteCategory = async (id: number) => {
-  const response = await apiRequest.delete(`/api/v1/categories/${id}`);
-  return response;
-};
+export const deleteCategory = async (id: number): Promise<void> => {
+  await apiRequest.delete(`/api/v1/categories/${id}`);
+}
apps/client/src/shared/apis/queries.ts (1)

36-40: useDeleteCategory: 키/함수 참조 간결화

mutationKey를 부여해 디버깅/개발자도구 추적성을 높이고, 화살표 대신 함수 참조로 간결화 제안.

-export const useDeleteCategory = () => {
-  return useMutation({
-    mutationFn: (id: number) => deleteCategory(id),
-  });
-};
+export const useDeleteCategory = () => {
+  return useMutation({
+    mutationKey: ['category.delete'],
+    mutationFn: deleteCategory,
+  });
+};
apps/client/src/shared/components/sidebar/Sidebar.tsx (1)

31-31: 변수명 충돌/가독성 개선: mutate 별칭 명확화

API 함수명과 동일한 deleteCategory 별칭은 혼동 여지 있습니다. mutateDeleteCategory 등으로 명확히 해주세요.

-  const { mutate: deleteCategory } = useDeleteCategory();
+  const { mutate: mutateDeleteCategory } = useDeleteCategory();
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d3a7096 and 6686ccf.

📒 Files selected for processing (3)
  • apps/client/src/shared/apis/axios.ts (1 hunks)
  • apps/client/src/shared/apis/queries.ts (2 hunks)
  • apps/client/src/shared/components/sidebar/Sidebar.tsx (4 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-07-17T09:18:13.818Z
Learnt from: constantly-dev
PR: Pinback-Team/pinback-client#102
File: apps/extension/src/components/modalPop/ModalPop.tsx:166-172
Timestamp: 2025-07-17T09:18:13.818Z
Learning: In apps/extension/src/components/modalPop/ModalPop.tsx, the categories array should include "안 읽은 정보" (Unread Information) as the first default category that cannot be deleted. This default category is used consistently across the client-side dashboard and should be protected from deletion in the extension as well.

Applied to files:

  • apps/client/src/shared/components/sidebar/Sidebar.tsx
🧬 Code graph analysis (2)
apps/client/src/shared/apis/queries.ts (1)
apps/client/src/shared/apis/axios.ts (1)
  • deleteCategory (42-45)
apps/client/src/shared/components/sidebar/Sidebar.tsx (2)
apps/client/src/shared/apis/axios.ts (1)
  • deleteCategory (42-45)
apps/client/src/shared/apis/queries.ts (1)
  • useDeleteCategory (36-40)
🔇 Additional comments (5)
apps/client/src/shared/apis/axios.ts (2)

31-35: 인터페이스 세미콜론 보강 LGTM

타입 선언 마무리 일관성 좋아졌습니다.


37-40: postSignUp 반환 구조 정돈 LGTM

구조분해로 data만 반환하는 형태 일관성 유지되어 좋습니다.

apps/client/src/shared/apis/queries.ts (1)

3-9: deleteCategory import 추가 LGTM

apps/client/src/shared/components/sidebar/Sidebar.tsx (2)

14-19: 훅 import 추가 LGTM

삭제 흐름 연결을 위한 훅 노출 사용 적절합니다.


189-190: PopupPortal onDeleteConfirm 시그니처 변경 확인 필요

onDeleteConfirm이 (id: number) => void로 변경된 것으로 보입니다. PopupPortal 선언(타입 정의 포함)과 모든 사용처가 이 시그니처로 일치하는지 확인하세요 — 참조: apps/client/src/shared/components/sidebar/Sidebar.tsx (약 189-190행). 자동 검색이 실패해 검증 불가; 변경된 선언 파일 경로 또는 검색 결과를 첨부하면 재검증합니다.

Comment on lines +87 to +97
const handleDeleteCategory = (id: number) => {
deleteCategory(id, {
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['dashboardCategories'] });
close();
},
onError: (error) => {
console.error('카테고리 삭제 실패:', error);
},
});
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

기본 카테고리 보호 및 선택 상태 정리 필요

장기 학습 노트에 따르면 "안 읽은 정보" 기본 카테고리는 삭제 금지입니다. 또한 삭제한 항목이 현재 선택되어 있으면 선택 해제 필요합니다.

-  const handleDeleteCategory = (id: number) => {
-    deleteCategory(id, {
+  const handleDeleteCategory = (id: number) => {
+    const name = getCategoryName(id);
+    if (name === '안 읽은 정보') {
+      console.warn('기본 카테고리는 삭제할 수 없습니다.');
+      return;
+    }
+    mutateDeleteCategory(id, {
       onSuccess: () => {
+        if (selectedCategoryId === id) {
+          setSelectedCategoryId(null);
+        }
         queryClient.invalidateQueries({ queryKey: ['dashboardCategories'] });
         close();
       },
       onError: (error) => {
         console.error('카테고리 삭제 실패:', error);
       },
     });
   };

옵션 메뉴에서 기본 카테고리에는 "삭제" 버튼 자체를 숨기는 UX 보완도 가능합니다. 원하시면 OptionsMenuPortal 조건 분기 패치 제안 드리겠습니다.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In apps/client/src/shared/components/sidebar/Sidebar.tsx around lines 87–97,
prevent deletion of the default "안 읽은 정보" category and clear selection if the
deleted category was selected: before calling deleteCategory, check whether the
target category is the default (compare id to the known defaultCategoryId or
category.isDefault flag) and bail out (or show a user-facing message) instead of
invoking delete; after successful deletion, if the app's current
selectedCategoryId equals the deleted id, call the selection reset handler
(e.g., setSelectedCategory(null) or selectDefaultCategory()) before calling
close() and invalidating queries; optionally, also hide the "Delete" option in
the OptionsMenuPortal for default categories by adding the same conditional
around the button render.

@jjangminii jjangminii changed the title feat: DeleteCategory 연결 Api(client): DeleteCategory 연결 Sep 13, 2025
Copy link
Member

@constantly-dev constantly-dev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

깔끔하네요 로직! 수고하셨습니다~~ 👍

@jjangminii jjangminii merged commit 9709082 into develop Sep 13, 2025
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api api 연결

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Api] 카테고리 삭제

2 participants