-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Feat] 결과 수정 페이지 api 연동, 기능 구현 #111
Conversation
Warning Rate limit exceeded@minseong0324 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 54 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (2)
Walkthrough이 PR은 결과 수정 페이지와 관련된 여러 컴포넌트와 훅에서 API 연동, 드래그 앤 드롭 기능 개선, 스타일 및 타입 보완 등의 변경 사항을 포함한다. Edit 컴포넌트의 구조가 단순화되었으며, 서버 사이드 토큰을 이용한 데이터 패칭, 새로운 custom hook 및 mutation/쿼리 훅이 추가되었다. TextField 컴포넌트에 새로운 variant가 도입되었고, DND 모듈의 import 구조 및 유틸리티 함수도 개선되었다. Changes
Sequence Diagram(s)sequenceDiagram
participant U as 사용자
participant E as Edit 컴포넌트
participant Q as useGetAllPostsQuery
participant A as API 서버
participant M as useUpdatePostsMutation
U->>E: 페이지 로드 요청
E->>Q: 게시물 데이터 요청 (getAllPostsQueryOptions)
Q->>A: GET /posts 요청
A-->>Q: 게시물 데이터 응답
Q-->>E: 데이터 전달 및 렌더링
U->>E: 드래그 앤 드롭 이벤트 발생
E->>M: onDragEnd 호출 (업데이트 페이로드 생성)
M->>A: PUT /posts 요청 (업데이트)
A-->>M: 업데이트 결과 반환
M-->>E: 상태 업데이트 후 재렌더링
Assessment against linked issues
Suggested reviewers
Poem
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (16)
apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/pageStyle.css.ts (1)
45-58
: 새로운 스타일 컴포넌트들이 잘 구조화되어 있습니다.새로 추가된 스타일들의 구조가 명확하고 재사용성이 높습니다:
accordionContentStyle
: 아코디언 내부 컨텐츠의 간격과 배치가 일관성 있게 정의됨contentInnerWrapper
: 높이 제어를 위한 독립적인 래퍼 스타일buttonWrapperStyle
: 버튼 정렬을 위한 명확한 스타일 정의한 가지 제안사항이 있습니다:
export const contentInnerWrapper = style({ height: '100%', + width: '100%', });
컨테이너의 전체 너비를 활용하여 더 일관된 레이아웃을 구성할 수 있습니다.
apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/Edit.tsx (2)
22-25
: 뮤테이션 이후 처리 검토가 필요합니다.
서버 업데이트에 성공 또는 실패했을 때 후속 액션(에러 표시, 메시지 노출 등)이 있는지 확인해주세요.
64-80
: Drag & Drop 후 서버 반영 로직이 적절합니다.
onDragEnd에서 items를 로컬 상태에 반영하고 곧바로 updatePosts를 호출해 순서를 동기화하고 있습니다. 다만 에러 시 재시도 로직이 필요한지 검토해 보세요.apps/web/src/hooks/useScroll.ts (1)
15-30
: 스크롤 이벤트 처리가 최적화되어 있습니다.requestAnimationFrame을 사용한 성능 최적화와 이벤트 리스너 정리가 잘 구현되어 있습니다. 다만, 브라우저 호환성을 위해 window.scrollY 사용 시 폴백(fallback) 처리를 고려해보세요.
- const scrollTop = window.scrollY || document.documentElement.scrollTop; + const scrollTop = window.pageYOffset ?? window.scrollY ?? document.documentElement.scrollTop;apps/web/src/store/mutation/useUpdatePostsMutation.ts (1)
33-37
: 에러 처리를 좀 더 구체화하면 좋을 것 같습니다.현재는 일반적인 Error 타입만 처리하고 있습니다. API 응답의 구체적인 에러 타입을 정의하고, 각 상황에 맞는 사용자 친화적인 에러 메시지를 표시하는 것이 좋을 것 같습니다.
- onError: (error) => { - if (error instanceof Error) { - toast.error(error.message); - } - }, + onError: (error) => { + if (error instanceof Error) { + if ('status' in error) { + switch (error.status) { + case 400: + toast.error('잘못된 요청입니다. 입력값을 확인해주세요.'); + break; + case 404: + toast.error('게시물을 찾을 수 없습니다.'); + break; + default: + toast.error('서버 오류가 발생했습니다. 잠시 후 다시 시도해주세요.'); + } + } else { + toast.error('알 수 없는 오류가 발생했습니다.'); + } + } + },packages/ui/src/components/TextField/TextFieldSubmit.tsx (1)
17-17
: variant 체크 로직을 개선하면 좋을 것 같습니다.하드코딩된 variant 체크는 유지보수가 어려울 수 있습니다. 허용된 variant 목록을 상수로 관리하는 것이 좋을 것 같습니다.
+const SUBMIT_BUTTON_VARIANTS = ['button', 'white'] as const; + - if (variant !== 'button' && variant !== 'white') return null; + if (!SUBMIT_BUTTON_VARIANTS.includes(variant)) return null;apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/_components/EditContent/EditContent.css.ts (1)
30-32
: 반응형 디자인 고려 필요고정된 너비 값(51.2rem)은 다양한 화면 크기에서 문제를 일으킬 수 있습니다. 반응형 디자인을 위해 상대적인 단위나 미디어 쿼리 사용을 고려해보세요.
export const accordionItemStyle = style({ - width: '51.2rem', + width: '100%', + maxWidth: '51.2rem', flex: '0 0 auto', });apps/web/src/store/mutation/useDeletePostMutation.ts (1)
31-35
: 에러 처리 개선 필요현재 Error 인스턴스만 처리하고 있습니다. 네트워크 오류나 다른 타입의 에러도 처리할 수 있도록 개선이 필요합니다.
onError: (error) => { + const errorMessage = error instanceof Error + ? error.message + : '게시글 삭제 중 오류가 발생했습니다.'; - if (error instanceof Error) { - toast.error(error.message); - } + toast.error(errorMessage); },apps/web/src/store/mutation/useCreateMorePostsMutation.ts (2)
29-33
: 성공 메시지 개선 필요성공 메시지에 하드코딩된 숫자(5개) 대신 실제 생성된 게시글 수를 표시하는 것이 좋습니다.
- onSuccess: () => { + onSuccess: (response) => { + const count = response.posts.length; - toast.success('게시글이 5개 추가됐어요!'); + toast.success(`게시글이 ${count}개 추가됐어요!`); queryClient.invalidateQueries( getAllPostsQueryOptions({ agentId, postGroupId }) ); },
35-39
: 에러 처리 개선 필요에러 처리가 Error 인스턴스로 제한되어 있습니다. 다양한 에러 상황에 대한 처리가 필요합니다.
onError: (error) => { + const errorMessage = error instanceof Error + ? error.message + : '게시글 생성 중 오류가 발생했습니다.'; - if (error instanceof Error) { - toast.error(error.message); - } + toast.error(errorMessage); },apps/web/src/store/query/useGetAllPostsQuery.ts (1)
12-13
: GC 시간 설정 검토 필요1분의 GC 시간은 다소 짧아 보입니다. 메모리 관리와 성능 최적화를 위해 더 긴 시간(예: 5-15분)을 고려해보세요.
-const STALE_TIME = 1000 * 60 * 1; -const GC_TIME = 1000 * 60 * 1; +const STALE_TIME = 1000 * 60 * 5; // 5분 +const GC_TIME = 1000 * 60 * 15; // 15분apps/web/src/types/post.ts (1)
33-48
: NewsCategory 타입에 대한 문서화 추가 필요각 카테고리 값의 의미와 사용 사례에 대한 설명이 있으면 좋을 것 같습니다.
+/** + * 뉴스 카테고리 타입 + * + * @property INVEST - 투자 관련 뉴스 + * @property STOCK - 주식 관련 뉴스 + * [... 다른 카테고리에 대한 설명 ...] + */ export type NewsCategory = | 'INVEST' | 'STOCK' // ...packages/ui/src/components/TextField/TextField.css.ts (1)
110-114
: isDisabled 스타일 중복 검토 필요
isError
와isDisabled
변형이 동일한 스타일을 가지고 있습니다. 코드 중복을 줄이기 위해 공통 스타일을 추출하는 것을 고려해보세요.variants: { + common: { + disabled: { + cursor: 'not-allowed', + }, + }, isError: { true: { - cursor: 'not-allowed', + ...common.disabled, }, }, isDisabled: { true: { - cursor: 'not-allowed', + ...common.disabled, }, }, },apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/_components/EditContent/EditContent.tsx (3)
3-18
: import 구문 최적화를 고려해보세요.현재 import 구문이 잘 구성되어 있지만, 다음과 같은 최적화를 고려해볼 수 있습니다:
- UI 컴포넌트들을 하나의 import 문으로 통합
- 관련된 mutation hook들을 하나의 파일로 통합하여 import
158-172
: TextField 컴포넌트의 사용자 경험을 개선할 수 있습니다.다음과 같은 UX 개선사항을 고려해보세요:
- 현재 입력 길이 표시 (maxLength와 함께)
- 입력값 유효성 검사 피드백
- placeholder 텍스트가 너무 길어 보임
211-224
: 업로드 준비 섹션의 사용자 경험을 개선할 수 있습니다.다음과 같은 개선사항을 고려해보세요:
- 드래그 가능한 아이템 수에 대한 시각적 피드백
- 업로드 가능한 최대/최소 아이템 수 표시
- 드래그 앤 드롭 동작 시 시각적 피드백 강화
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (21)
apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/Edit.tsx
(3 hunks)apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/_components/EditContent/EditContent.css.ts
(1 hunks)apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/_components/EditContent/EditContent.tsx
(1 hunks)apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/_components/SkeletonItems/SkeletonItems.tsx
(1 hunks)apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/page.tsx
(1 hunks)apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/pageStyle.css.ts
(2 hunks)apps/web/src/app/create/pageStyle.css.ts
(1 hunks)apps/web/src/app/page.tsx
(1 hunks)apps/web/src/components/common/DNDController/context/DndContext.tsx
(1 hunks)apps/web/src/components/common/DNDController/hooks/useDragAndDrop.ts
(4 hunks)apps/web/src/hooks/useScroll.ts
(1 hunks)apps/web/src/store/mutation/useCreateMorePostsMutation.ts
(1 hunks)apps/web/src/store/mutation/useDeletePostMutation.ts
(1 hunks)apps/web/src/store/mutation/useUpdatePostsMutation.ts
(1 hunks)apps/web/src/store/mutation/useUpdatePromptMutation.ts
(1 hunks)apps/web/src/store/query/useGetAllPostsQuery.ts
(1 hunks)apps/web/src/types/post.ts
(2 hunks)packages/ui/src/components/TextField/TextField.css.ts
(4 hunks)packages/ui/src/components/TextField/TextFieldInput.tsx
(0 hunks)packages/ui/src/components/TextField/TextFieldSubmit.tsx
(1 hunks)packages/ui/src/components/TextField/context.ts
(1 hunks)
💤 Files with no reviewable changes (1)
- packages/ui/src/components/TextField/TextFieldInput.tsx
✅ Files skipped from review due to trivial changes (1)
- apps/web/src/app/page.tsx
🔇 Additional comments (22)
apps/web/src/app/create/pageStyle.css.ts (1)
5-7
: 스타일 변경이 적절합니다!
height: '100vh'
에서minHeight: '100vh'
로의 변경은 다음과 같은 이점이 있습니다:
- 컨텐츠가 viewport 높이보다 커질 때 자연스럽게 확장 가능
- 반응형 디자인에 더 적합한 접근 방식
apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/pageStyle.css.ts (1)
5-12
: 메인 스타일 변경사항이 개선되었습니다.레이아웃 구조가 다음과 같이 개선되었습니다:
maxWidth
와minHeight
를 사용하여 더 유연한 레이아웃 구현paddingTop
으로 상단 여백 확보overflowY
로 수직 스크롤만 제어하여 성능 최적화apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/Edit.tsx (8)
6-8
: 임포트 구조가 간결해졌습니다.
필요한 컴포넌트만 임포트하여 가독성과 유지보수성 모두 좋아 보입니다.
10-14
: 쿼리와 뮤테이션 의존성을 명확히 분리하였습니다.
useGetAllPostsQuery와 useUpdatePostsMutation을 별도의 파일로 임포트해 각각 사용하므로, 역할이 구분되어 있고 유지보수에 용이해 보입니다.
16-17
: useScroll 훅 활용이 인상적입니다.
스크롤 위치에 따라 UI 상태를 조절하는 로직이 분리되어, 가독성과 재사용성 면에서 좋습니다.
18-21
: 쿼리 데이터를 안전하게 구조 분해 할당하고 있습니다.
posts가 없을 때를 고려한 에러 처리나 로딩 상태도 함께 관리하고 있는지 확인 부탁드립니다.
26-26
: 라우팅 로직이 간결합니다.
Next.js의 useRouter를 활용해 직관적인 페이지 이동이 가능합니다.
28-28
: 로컬 상태 관리에 유의하세요.
서버로부터 재페치 시점에 따라 posts 데이터가 갱신될 경우, items 상태와 동기화가 필요할 수 있습니다.
33-35
: 업로드 가능한 게시물을 효율적으로 확인 중입니다.
.some() 메서드를 통해 조건 검증이 간결하게 처리되어 가독성이 뛰어납니다.
52-55
: 버튼의 활성 상태와 라우팅 처리가 명확합니다.
READY_TO_UPLOAD 상태인 게시물이 없으면 예약 페이지로 이동할 수 없도록 해, UX 면에서 안전장치가 잘 되어 있습니다.packages/ui/src/components/TextField/context.ts (1)
3-3
: TextFieldVariant에 'white' 추가가 완료되었습니다.
새로운 배경 스타일이 필요한 경우를 지원해주므로, 호환되는 스타일이나 타입 정의가 모두 반영되었는지 점검 부탁드립니다.apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/_components/SkeletonItems/SkeletonItems.tsx (1)
1-21
: Skeleton 컴포넌트가 명확하게 작성되었습니다.
length만큼 DndController.Item을 생성하며, 로딩 상태(isLoading)를 시각적으로 표현하기에 적절한 구현으로 보입니다.apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/page.tsx (1)
7-20
: 서버 사이드 데이터 페칭 구현이 잘 되어있습니다!서버 토큰을 가져오고 쿼리 옵션을 설정하는 로직이 깔끔하게 구현되어 있으며, ServerFetchBoundary를 통한 데이터 페칭 처리가 적절합니다.
packages/ui/src/components/TextField/TextFieldSubmit.tsx (1)
20-32
: 접근성 고려가 잘 되어있습니다!disabled 상태에 따른 스타일 변경과 아이콘 색상 처리가 잘 구현되어 있습니다. 사용자 경험을 고려한 좋은 구현입니다.
apps/web/src/store/query/useGetAllPostsQuery.ts (1)
24-46
: 함수 구현이 깔끔하고 문서화가 잘 되어있습니다.쿼리 키 구조와 타입 정의가 명확하며, 한글 문서화가 잘 되어 있습니다.
apps/web/src/types/post.ts (1)
52-61
: PostGroup 인터페이스 구현이 잘 되어있습니다.필요한 모든 필드가 명확하게 정의되어 있으며, 타입 안전성이 잘 보장되어 있습니다.
apps/web/src/components/common/DNDController/context/DndContext.tsx (1)
80-82
: 자동 스크롤 비활성화에 대한 검토 필요자동 스크롤을 비활성화하면 긴 목록에서의 드래그 앤 드롭 사용성이 저하될 수 있습니다. 사용자 경험 관점에서 이 설정의 영향을 검토해보세요.
packages/ui/src/components/TextField/TextField.css.ts (1)
32-36
: white 변형 스타일이 잘 구현되어 있습니다.색상과 테두리 스타일이 일관성 있게 적용되어 있으며, 변수 사용이 적절합니다.
apps/web/src/components/common/DNDController/hooks/useDragAndDrop.ts (4)
9-9
: 타입 시그니처 개선이 이루어졌습니다.
onDragEnd
콜백이 업데이트된 아이템 배열을 받도록 변경되어 상태 관리가 더욱 용이해졌습니다.
20-23
: 상태 동기화 로직이 적절하게 구현되었습니다.
initialItems
가 변경될 때마다items
상태를 업데이트하는useEffect
가 추가되어 props와 로컬 상태의 동기화가 보장됩니다.
113-117
: 드래그 앤 드롭 상태 업데이트 로직이 개선되었습니다.아이템 상태 업데이트 로직이 단순화되었고, 상태 변경 사항이
onDragEnd
콜백을 통해 적절하게 전파됩니다.
128-130
: 배열 조작 로직이 일관성 있게 구현되었습니다.배열 이동 로직이 단순화되었고, 상태 업데이트와 콜백 호출이 일관되게 처리됩니다.
return useMutation({ | ||
mutationFn: (data: UpdatePromptRequest) => | ||
PATCH(`agents/${agentId}/post-groups/${postGroupId}/posts/prompt`, data), | ||
onSuccess: () => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
입력 데이터 유효성 검사 추가 필요
mutationFn에서 데이터 유효성 검사가 누락되어 있습니다. prompt가 비어있거나 postsId 배열이 비어있는 경우를 처리해야 합니다.
mutationFn: (data: UpdatePromptRequest) => {
+ if (!data.prompt.trim()) {
+ throw new Error('프롬프트를 입력해주세요.');
+ }
+ if (data.postsId.length === 0) {
+ throw new Error('수정할 게시글을 선택해주세요.');
+ }
return PATCH(`agents/${agentId}/post-groups/${postGroupId}/posts/prompt`, data);
},
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
return useMutation({ | |
mutationFn: (data: UpdatePromptRequest) => | |
PATCH(`agents/${agentId}/post-groups/${postGroupId}/posts/prompt`, data), | |
onSuccess: () => { | |
return useMutation({ | |
mutationFn: (data: UpdatePromptRequest) => { | |
if (!data.prompt.trim()) { | |
throw new Error('프롬프트를 입력해주세요.'); | |
} | |
if (data.postsId.length === 0) { | |
throw new Error('수정할 게시글을 선택해주세요.'); | |
} | |
return PATCH(`agents/${agentId}/post-groups/${postGroupId}/posts/prompt`, data); | |
}, | |
onSuccess: () => { |
const onSubmit = (data: PromptForm) => { | ||
const editingPostIds = getItemsByStatus(POST_STATUS.EDITING).map( | ||
(item) => item.id | ||
); | ||
|
||
updatePrompt({ | ||
prompt: data.prompt, | ||
postsId: editingPostIds, | ||
}); | ||
setValue('prompt', ''); | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
폼 제출 시 에러 처리를 추가하는 것이 좋습니다.
현재 구현에 다음 사항들을 추가하면 좋을 것 같습니다:
- 빈 prompt 체크
- editingPostIds가 비어있는 경우 처리
- mutation 실패 시 에러 처리
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🧹 Nitpick comments (4)
apps/web/src/components/common/DNDController/utils/createItemsByStatus.ts (1)
3-14
: 타입 안전성과 에러 처리를 개선하면 좋을 것 같습니다.현재 구현은 잘 작동하지만, 다음과 같은 개선사항을 고려해보세요:
- 초기값 타입 안전성
- 빈 배열 처리
다음과 같이 개선할 수 있습니다:
export function createItemsByStatus( items: Post[] ): Record<Post['status'], Post[]> { + if (!items?.length) { + return {} as Record<Post['status'], Post[]>; + } + return items.reduce( (acc, item) => { if (!acc[item.status]) acc[item.status] = []; acc[item.status].push(item); return acc; }, - {} as Record<Post['status'], Post[]> + Object.fromEntries( + Object.values(POST_STATUS).map(status => [status, []]) + ) as Record<Post['status'], Post[]> ); }apps/web/src/store/mutation/useCreateMorePostsMutation.ts (1)
54-66
: 매직 넘버를 상수로 분리하면 좋을 것 같습니다.스켈레톤 포스트 생성 로직에서 하드코딩된 숫자를 상수로 분리하면 유지보수가 더 쉬워질 것 같습니다.
+const SKELETON_POST_COUNT = 5; + -const skeletonPosts: Post[] = Array.from({ length: 5 }).map( +const skeletonPosts: Post[] = Array.from({ length: SKELETON_POST_COUNT }).map(apps/web/src/components/common/DNDController/hooks/useDragAndDrop.ts (2)
45-117
: 드래그 오버 핸들러의 문서화가 필요합니다.handleDragOver 함수의 로직이 잘 구현되어 있지만, 복잡한 로직의 이해를 돕기 위해 각 분기점에 대한 추가 설명이 필요합니다.
다음과 같이 주요 로직에 대한 설명을 추가하는 것을 제안합니다:
const handleDragOver = (event: DragOverEvent) => { + // 드래그 오버 이벤트 처리 + // 1. 아이템 위로 드래그하는 경우 + // - 같은 상태 내에서의 이동: 순서만 변경 + // - 다른 상태로의 이동: 상태 변경 및 순서 조정 + // 2. 컨테이너로 드래그하는 경우 + // - 해당 상태의 마지막으로 이동 const { active, over } = event; // ... rest of the code
119-186
: 드래그 종료 핸들러의 중복 로직을 개선할 수 있습니다.handleDragEnd 함수 내의 displayOrder 업데이트 로직이 여러 곳에서 반복됩니다. 이를 공통 함수로 추출하면 코드의 재사용성과 유지보수성이 향상될 것입니다.
다음과 같은 리팩토링을 제안합니다:
+const updateItemsAndNotify = ( + itemsByStatus: Record<string, Post[]>, + onDragEnd?: (items: Post[]) => void +) => { + const newItems = updateDisplayOrders(Object.values(itemsByStatus).flat()); + onDragEnd?.(newItems); + return newItems; +}; const handleDragEnd = (event: DragEndEvent) => { // ... existing code ... - const newItems = updateDisplayOrders(Object.values(itemsByStatus).flat()); - onDragEnd?.(newItems); - return newItems; + return updateItemsAndNotify(itemsByStatus, onDragEnd); };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (14)
apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/Edit.tsx
(3 hunks)apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/_components/EditContent/EditContent.tsx
(1 hunks)apps/web/src/components/common/DNDController/DndController.tsx
(2 hunks)apps/web/src/components/common/DNDController/compounds/index.ts
(1 hunks)apps/web/src/components/common/DNDController/context/DndContext.tsx
(2 hunks)apps/web/src/components/common/DNDController/context/index.ts
(1 hunks)apps/web/src/components/common/DNDController/hooks/index.ts
(1 hunks)apps/web/src/components/common/DNDController/hooks/useDragAndDrop.ts
(4 hunks)apps/web/src/components/common/DNDController/index.ts
(1 hunks)apps/web/src/components/common/DNDController/utils/createItemsByStatus.ts
(1 hunks)apps/web/src/components/common/DNDController/utils/index.ts
(1 hunks)apps/web/src/store/mutation/useCreateMorePostsMutation.ts
(1 hunks)apps/web/src/store/mutation/useUpdatePostsMutation.ts
(1 hunks)apps/web/src/types/post.ts
(2 hunks)
✅ Files skipped from review due to trivial changes (5)
- apps/web/src/components/common/DNDController/hooks/index.ts
- apps/web/src/components/common/DNDController/utils/index.ts
- apps/web/src/components/common/DNDController/index.ts
- apps/web/src/components/common/DNDController/DndController.tsx
- apps/web/src/components/common/DNDController/compounds/index.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- apps/web/src/components/common/DNDController/context/DndContext.tsx
- apps/web/src/store/mutation/useUpdatePostsMutation.ts
- apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/_components/EditContent/EditContent.tsx
- apps/web/src/types/post.ts
🔇 Additional comments (5)
apps/web/src/components/common/DNDController/context/index.ts (1)
1-3
: 깔끔한 컨텍스트 내보내기 구조입니다!컨텍스트 관련 컴포넌트와 훅을 중앙에서 관리하는 barrel 파일의 구조가 잘 구성되어 있습니다.
apps/web/src/components/common/DNDController/hooks/useDragAndDrop.ts (4)
7-11
: 타입 시그니처가 개선되었습니다.onDragEnd 콜백에 items 매개변수를 추가함으로써 드래그 앤 드롭 작업 후의 상태 변경을 더 명확하게 처리할 수 있게 되었습니다.
13-24
: displayOrder 업데이트 로직이 잘 구현되었습니다.각 상태별로 아이템을 정렬하고 displayOrder를 재계산하는 로직이 깔끔하게 구현되었습니다.
34-37
: 상태 동기화가 적절하게 구현되었습니다.initialItems prop이 변경될 때마다 내부 상태를 업데이트하는 useEffect 구현이 적절합니다.
39-43
: 유틸리티 함수들이 잘 구현되었습니다.getItemsByStatus와 handleRemove 함수가 간결하고 목적에 맞게 잘 구현되었습니다.
Also applies to: 188-195
<DndController | ||
initialItems={posts.data.posts} | ||
onDragEnd={(updatedItems) => { | ||
const updatePayload = { | ||
posts: updatedItems.map((item) => ({ | ||
postId: item.id, | ||
status: item.status, | ||
displayOrder: item.displayOrder, | ||
uploadTime: item.uploadTime, | ||
})), | ||
}; | ||
|
||
{/* 수정 중인 글 영역 */} | ||
<Accordion.Item | ||
value={POST_STATUS.EDITING} | ||
className={style.accordionItemStyle} | ||
> | ||
<Accordion.Trigger className={style.accordionTriggerStyle}> | ||
<Chip variant="purple">수정 중인 글</Chip> | ||
</Accordion.Trigger> | ||
<Accordion.Content id={POST_STATUS.EDITING}> | ||
<DndController.Droppable id={POST_STATUS.EDITING}> | ||
<DndController.SortableList | ||
items={getItemsByStatus(POST_STATUS.EDITING).map( | ||
(item) => item.id | ||
)} | ||
> | ||
{getItemsByStatus(POST_STATUS.EDITING).length > 0 ? ( | ||
getItemsByStatus(POST_STATUS.EDITING).map((item) => ( | ||
<DndController.Item | ||
key={item.id} | ||
id={item.id} | ||
summary={item.summary} | ||
updatedAt={item.updatedAt} | ||
onRemove={() => handleRemove(item.id)} | ||
onModify={() => {}} | ||
/> | ||
)) | ||
) : ( | ||
<DragGuide description="수정 중인 글을 끌어서 여기에 놓아주세요" /> | ||
)} | ||
</DndController.SortableList> | ||
</DndController.Droppable> | ||
</Accordion.Content> | ||
</Accordion.Item> | ||
|
||
{/* 업로드할 글 영역 */} | ||
<Accordion.Item | ||
value={POST_STATUS.READY_TO_UPLOAD} | ||
className={style.accordionItemStyle} | ||
> | ||
<Accordion.Trigger className={style.accordionTriggerStyle}> | ||
<Chip variant="green">업로드할 글</Chip> | ||
</Accordion.Trigger> | ||
<Accordion.Content id={POST_STATUS.READY_TO_UPLOAD}> | ||
<DndController.Droppable id={POST_STATUS.READY_TO_UPLOAD}> | ||
<DndController.SortableList | ||
items={getItemsByStatus(POST_STATUS.READY_TO_UPLOAD).map( | ||
(item) => item.id | ||
)} | ||
> | ||
{getItemsByStatus(POST_STATUS.READY_TO_UPLOAD).length > 0 ? ( | ||
getItemsByStatus(POST_STATUS.READY_TO_UPLOAD).map( | ||
(item) => ( | ||
<DndController.Item | ||
key={item.id} | ||
id={item.id} | ||
summary={item.summary} | ||
updatedAt={item.updatedAt} | ||
onRemove={() => handleRemove(item.id)} | ||
onModify={() => {}} | ||
/> | ||
) | ||
) | ||
) : ( | ||
<DragGuide description="업로드가 준비된 글을 끌어서 여기에 놓아주세요" /> | ||
)} | ||
</DndController.SortableList> | ||
</DndController.Droppable> | ||
</Accordion.Content> | ||
</Accordion.Item> | ||
</Accordion> | ||
</div> | ||
updatePosts(updatePayload); | ||
}} | ||
> | ||
<EditContent agentId={agentId} postGroupId={postGroupId} /> | ||
</DndController> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
업데이트 요청의 경쟁 상태를 방지해야 합니다.
드래그 앤 드롭 이벤트로 인한 연속적인 업데이트 요청이 발생할 수 있습니다.
다음과 같이 디바운스를 적용하는 것을 추천드립니다:
+import { debounce } from 'lodash';
+
<DndController
initialItems={posts.data.posts}
- onDragEnd={(updatedItems) => {
+ onDragEnd={debounce((updatedItems) => {
const updatePayload = {
posts: updatedItems.map((item) => ({
postId: item.id,
status: item.status,
displayOrder: item.displayOrder,
uploadTime: item.uploadTime,
})),
};
updatePosts(updatePayload);
- }}
+ }, 300)}
>
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
<DndController | |
initialItems={posts.data.posts} | |
onDragEnd={(updatedItems) => { | |
const updatePayload = { | |
posts: updatedItems.map((item) => ({ | |
postId: item.id, | |
status: item.status, | |
displayOrder: item.displayOrder, | |
uploadTime: item.uploadTime, | |
})), | |
}; | |
{/* 수정 중인 글 영역 */} | |
<Accordion.Item | |
value={POST_STATUS.EDITING} | |
className={style.accordionItemStyle} | |
> | |
<Accordion.Trigger className={style.accordionTriggerStyle}> | |
<Chip variant="purple">수정 중인 글</Chip> | |
</Accordion.Trigger> | |
<Accordion.Content id={POST_STATUS.EDITING}> | |
<DndController.Droppable id={POST_STATUS.EDITING}> | |
<DndController.SortableList | |
items={getItemsByStatus(POST_STATUS.EDITING).map( | |
(item) => item.id | |
)} | |
> | |
{getItemsByStatus(POST_STATUS.EDITING).length > 0 ? ( | |
getItemsByStatus(POST_STATUS.EDITING).map((item) => ( | |
<DndController.Item | |
key={item.id} | |
id={item.id} | |
summary={item.summary} | |
updatedAt={item.updatedAt} | |
onRemove={() => handleRemove(item.id)} | |
onModify={() => {}} | |
/> | |
)) | |
) : ( | |
<DragGuide description="수정 중인 글을 끌어서 여기에 놓아주세요" /> | |
)} | |
</DndController.SortableList> | |
</DndController.Droppable> | |
</Accordion.Content> | |
</Accordion.Item> | |
{/* 업로드할 글 영역 */} | |
<Accordion.Item | |
value={POST_STATUS.READY_TO_UPLOAD} | |
className={style.accordionItemStyle} | |
> | |
<Accordion.Trigger className={style.accordionTriggerStyle}> | |
<Chip variant="green">업로드할 글</Chip> | |
</Accordion.Trigger> | |
<Accordion.Content id={POST_STATUS.READY_TO_UPLOAD}> | |
<DndController.Droppable id={POST_STATUS.READY_TO_UPLOAD}> | |
<DndController.SortableList | |
items={getItemsByStatus(POST_STATUS.READY_TO_UPLOAD).map( | |
(item) => item.id | |
)} | |
> | |
{getItemsByStatus(POST_STATUS.READY_TO_UPLOAD).length > 0 ? ( | |
getItemsByStatus(POST_STATUS.READY_TO_UPLOAD).map( | |
(item) => ( | |
<DndController.Item | |
key={item.id} | |
id={item.id} | |
summary={item.summary} | |
updatedAt={item.updatedAt} | |
onRemove={() => handleRemove(item.id)} | |
onModify={() => {}} | |
/> | |
) | |
) | |
) : ( | |
<DragGuide description="업로드가 준비된 글을 끌어서 여기에 놓아주세요" /> | |
)} | |
</DndController.SortableList> | |
</DndController.Droppable> | |
</Accordion.Content> | |
</Accordion.Item> | |
</Accordion> | |
</div> | |
updatePosts(updatePayload); | |
}} | |
> | |
<EditContent agentId={agentId} postGroupId={postGroupId} /> | |
</DndController> | |
import { debounce } from 'lodash'; | |
<DndController | |
initialItems={posts.data.posts} | |
onDragEnd={debounce((updatedItems) => { | |
const updatePayload = { | |
posts: updatedItems.map((item) => ({ | |
postId: item.id, | |
status: item.status, | |
displayOrder: item.displayOrder, | |
uploadTime: item.uploadTime, | |
})), | |
}; | |
updatePosts(updatePayload); | |
}, 300)} | |
> | |
<EditContent agentId={agentId} postGroupId={postGroupId} /> | |
</DndController> |
const { data: posts } = useGetAllPostsQuery({ | ||
agentId, | ||
postGroupId, | ||
}); | ||
const { mutate: updatePosts } = useUpdatePostsMutation({ | ||
agentId, | ||
postGroupId, | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
로딩 및 에러 상태 처리가 필요합니다.
데이터 페칭 시 로딩 상태와 에러 상태 처리가 누락되어 있습니다.
다음과 같이 개선하세요:
- const { data: posts } = useGetAllPostsQuery({
+ const { data: posts, isLoading, error } = useGetAllPostsQuery({
agentId,
postGroupId,
});
const { mutate: updatePosts } = useUpdatePostsMutation({
agentId,
postGroupId,
});
+
+ if (isLoading) return <LoadingSpinner />;
+ if (error) return <ErrorComponent message={error.message} />;
+ if (!posts?.data?.posts) return null;
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const { data: posts } = useGetAllPostsQuery({ | |
agentId, | |
postGroupId, | |
}); | |
const { mutate: updatePosts } = useUpdatePostsMutation({ | |
agentId, | |
postGroupId, | |
}); | |
const { data: posts, isLoading, error } = useGetAllPostsQuery({ | |
agentId, | |
postGroupId, | |
}); | |
const { mutate: updatePosts } = useUpdatePostsMutation({ | |
agentId, | |
postGroupId, | |
}); | |
if (isLoading) return <LoadingSpinner />; | |
if (error) return <ErrorComponent message={error.message} />; | |
if (!posts?.data?.posts) return null; |
onError: (error, _, context) => { | ||
// 에러 발생 시 이전 상태로 롤백 | ||
if (context?.previousData) { | ||
queryClient.setQueryData( | ||
getAllPostsQueryOptions({ agentId, postGroupId }).queryKey, | ||
context.previousData | ||
); | ||
} | ||
if (error instanceof Error) { | ||
toast.error(error.message); | ||
} | ||
}, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
에러 복구 로직을 강화하면 좋을 것 같습니다.
현재 에러 처리는 기본적인 수준입니다. 재시도 로직을 추가하면 더 견고해질 것 같습니다.
return useMutation({
+ retry: 3,
+ retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
onError: (error, _, context) => {
if (context?.previousData) {
queryClient.setQueryData(
getAllPostsQueryOptions({ agentId, postGroupId }).queryKey,
context.previousData
);
}
if (error instanceof Error) {
- toast.error(error.message);
+ toast.error(`게시글 추가 중 오류가 발생했습니다: ${error.message}`);
}
},
});
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
onError: (error, _, context) => { | |
// 에러 발생 시 이전 상태로 롤백 | |
if (context?.previousData) { | |
queryClient.setQueryData( | |
getAllPostsQueryOptions({ agentId, postGroupId }).queryKey, | |
context.previousData | |
); | |
} | |
if (error instanceof Error) { | |
toast.error(error.message); | |
} | |
}, | |
return useMutation({ | |
retry: 3, | |
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000), | |
onError: (error, _, context) => { | |
// 에러 발생 시 이전 상태로 롤백 | |
if (context?.previousData) { | |
queryClient.setQueryData( | |
getAllPostsQueryOptions({ agentId, postGroupId }).queryKey, | |
context.previousData | |
); | |
} | |
if (error instanceof Error) { | |
toast.error(`게시글 추가 중 오류가 발생했습니다: ${error.message}`); | |
} | |
}, | |
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (3)
apps/web/src/store/mutation/useCreateMorePostsMutation.ts (3)
34-37
: 에러 메시지를 더 명확하게 개선하면 좋을 것 같습니다.현재 에러 메시지가 제한 사항만 언급하고 있습니다. 현재 게시글 수와 최대 제한을 함께 표시하면 사용자가 더 잘 이해할 수 있을 것 같습니다.
- toast.error('게시글은 25개까지만 생성할 수 있어요.'); - throw new Error('게시글은 25개까지만 생성할 수 있어요.'); + const currentCount = posts.data.posts.length; + toast.error(`현재 게시글 ${currentCount}개 / 최대 25개까지만 생성할 수 있어요.`); + throw new Error(`현재 게시글 ${currentCount}개 / 최대 25개까지만 생성할 수 있어요.`);
54-85
: 타입 안전성을 개선하면 좋을 것 같습니다.낙관적 업데이트 로직에서
old
데이터의 타입 체크를 더 강화하면 좋을 것 같습니다.- if (!old) return old; + if (!old?.data?.posts) return old;
89-107
: 에러 처리를 더 구체적으로 개선하면 좋을 것 같습니다.현재는 일반적인 Error 인스턴스만 체크하고 있습니다. 네트워크 오류나 서버 오류 등 구체적인 에러 케이스를 구분하여 처리하면 좋을 것 같습니다.
if (error instanceof Error) { - toast.error(error.message); + if (error.name === 'NetworkError') { + toast.error('네트워크 연결을 확인해주세요.'); + } else if (error.name === 'ServerError') { + toast.error('서버에 문제가 발생했습니다. 잠시 후 다시 시도해주세요.'); + } else { + toast.error(error.message); + } }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/_components/EditContent/EditContent.tsx
(1 hunks)apps/web/src/store/mutation/useCreateMorePostsMutation.ts
(1 hunks)apps/web/src/store/query/useGetAllPostsQuery.ts
(1 hunks)apps/web/src/types/post.ts
(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- apps/web/src/store/query/useGetAllPostsQuery.ts
- apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/_components/EditContent/EditContent.tsx
- apps/web/src/types/post.ts
🔇 Additional comments (2)
apps/web/src/store/mutation/useCreateMorePostsMutation.ts (2)
1-18
: 코드가 깔끔하고 잘 구성되어 있습니다!필요한 모든 의존성이 적절히 import 되어 있고,
CreateMorePostsResponse
인터페이스가 명확하게 정의되어 있습니다.
31-42
: 재시도 로직 추가가 필요합니다.현재 에러 처리는 기본적인 수준입니다. 재시도 로직을 추가하면 더 견고해질 것 같습니다.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
♻️ Duplicate comments (2)
apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/Edit.tsx (2)
18-25
:⚠️ Potential issue로딩 및 에러 상태 처리가 필요합니다.
데이터 페칭 시 로딩 상태와 에러 상태 처리가 누락되어 있습니다.
69-89
:⚠️ Potential issue업데이트 요청의 경쟁 상태를 방지해야 합니다.
드래그 앤 드롭 이벤트로 인한 연속적인 업데이트 요청이 발생할 수 있습니다.
🧹 Nitpick comments (2)
apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/Edit.tsx (2)
3-15
: import 문을 타입별로 그룹화하는 것이 좋습니다.import 문을 다음과 같은 순서로 그룹화하여 가독성을 향상시키는 것을 추천드립니다:
- React 관련
- 외부 라이브러리
- 내부 컴포넌트
- 타입
- 스타일
'use client'; + // React & External libraries import { useRouter } from 'next/navigation'; import { useScroll } from '@web/hooks'; + + // Internal components import { NavBar, MainBreadcrumbItem } from '@web/components/common'; import { Breadcrumb, Button, Icon } from '@repo/ui'; import { DndController } from '@web/components/common'; import { EditContent } from './_components/EditContent/EditContent'; + + // Types import { POST_STATUS, SKELETON_STATUS } from '@web/types/post'; import { EditPageParams } from './types'; + + // Queries & Mutations import { useGetAllPostsQuery } from '@web/store/query/useGetAllPostsQuery'; import { useUpdatePostsMutation } from '@web/store/mutation/useUpdatePostsMutation'; + + // Styles import * as style from './pageStyle.css';
31-40
: 상태 확인 로직을 커스텀 훅으로 분리하면 좋을 것 같습니다.posts 배열의 상태를 확인하는 로직을 재사용 가능한 커스텀 훅으로 분리하면 코드의 재사용성과 테스트 용이성이 향상될 것 같습니다.
function usePostsStatus(posts: Post[]) { const hasReadyToUploadPosts = posts.some( (post) => post.status === POST_STATUS.READY_TO_UPLOAD ); const isGenerating = posts.some( (post) => post.uploadTime === SKELETON_STATUS ); return { hasReadyToUploadPosts, isGenerating }; }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/Edit.tsx
(3 hunks)apps/web/src/components/common/DNDController/context/DndContext.tsx
(5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/web/src/components/common/DNDController/context/DndContext.tsx
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🧹 Nitpick comments (1)
apps/web/src/store/mutation/useCreateMorePostsMutation.ts (1)
43-88
: 주석 처리된 낙관적 업데이트 로직을 활성화하는 것이 좋습니다.낙관적 업데이트를 구현하면 사용자 경험이 향상될 것 같습니다. 주석을 해제하고 로직을 활성화하는 것을 추천드립니다.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/_components/EditContent/EditContent.tsx
(1 hunks)apps/web/src/store/mutation/useCreateMorePostsMutation.ts
(1 hunks)
🔇 Additional comments (3)
apps/web/src/store/mutation/useCreateMorePostsMutation.ts (1)
101-107
: 성공 처리 로직이 적절합니다.성공 시 토스트 메시지를 표시하고 쿼리를 무효화하여 최신 데이터를 가져오는 로직이 잘 구현되어 있습니다.
apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/_components/EditContent/EditContent.tsx (2)
33-46
: 로딩 상태 관리가 잘 구현되어 있습니다.여러 mutation의 로딩 상태를 하나의 변수로 통합하여 관리하는 방식이 깔끔합니다.
73-83
:⚠️ Potential issue폼 제출 시 유효성 검사가 필요합니다.
현재 구현에서는 다음과 같은 유효성 검사가 누락되어 있습니다:
- 빈 prompt 체크
- editingPostIds가 비어있는 경우 처리
다음과 같이 개선하는 것을 제안드립니다:
const onSubmit = (data: PromptForm) => { const editingPostIds = getItemsByStatus(POST_STATUS.EDITING).map( (item) => item.id ); + if (!data.prompt.trim()) { + toast.error('프롬프트를 입력해주세요.'); + return; + } + + if (editingPostIds.length === 0) { + toast.error('수정할 게시글을 선택해주세요.'); + return; + } updatePrompt({ prompt: data.prompt, postsId: editingPostIds, }); setValue('prompt', ''); };Likely invalid or redundant comment.
return useMutation({ | ||
mutationFn: () => { | ||
// eof가 true이면 더 이상 생성할 수 없음 | ||
if (posts.data.postGroup.eof) { | ||
toast.error('게시글은 25개까지만 생성할 수 있어요.'); | ||
throw new Error('게시글은 25개까지만 생성할 수 있어요.'); | ||
} | ||
|
||
return POST<CreateMorePostsResponse>( | ||
`agents/${agentId}/post-groups/${postGroupId}/posts` | ||
); | ||
}, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
에러 처리 로직이 개선되어야 합니다.
현재 구현된 에러 처리는 25개 제한에 대해서만 처리하고 있습니다. 네트워크 오류나 서버 오류 등 다른 예외 상황에 대한 처리도 필요합니다.
다음과 같이 개선하는 것을 제안드립니다:
return useMutation({
+ retry: 3,
+ retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
mutationFn: () => {
if (posts.data.postGroup.eof) {
toast.error('게시글은 25개까지만 생성할 수 있어요.');
throw new Error('게시글은 25개까지만 생성할 수 있어요.');
}
return POST<CreateMorePostsResponse>(
`agents/${agentId}/post-groups/${postGroupId}/posts`
- );
+ ).catch((error) => {
+ toast.error('게시글 생성 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.');
+ throw error;
+ });
},
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
return useMutation({ | |
mutationFn: () => { | |
// eof가 true이면 더 이상 생성할 수 없음 | |
if (posts.data.postGroup.eof) { | |
toast.error('게시글은 25개까지만 생성할 수 있어요.'); | |
throw new Error('게시글은 25개까지만 생성할 수 있어요.'); | |
} | |
return POST<CreateMorePostsResponse>( | |
`agents/${agentId}/post-groups/${postGroupId}/posts` | |
); | |
}, | |
return useMutation({ | |
retry: 3, | |
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000), | |
mutationFn: () => { | |
// eof가 true이면 더 이상 생성할 수 없음 | |
if (posts.data.postGroup.eof) { | |
toast.error('게시글은 25개까지만 생성할 수 있어요.'); | |
throw new Error('게시글은 25개까지만 생성할 수 있어요.'); | |
} | |
return POST<CreateMorePostsResponse>( | |
`agents/${agentId}/post-groups/${postGroupId}/posts` | |
).catch((error) => { | |
toast.error('게시글 생성 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.'); | |
throw error; | |
}); | |
}, | |
}); |
<TextField variant="white"> | ||
<TextField.Input | ||
{...register('prompt')} | ||
value={promptValue} | ||
onChange={(e) => setValue('prompt', e.target.value)} | ||
placeholder="AI에게 요청하여 글 업그레이드하기" | ||
sumbitButton={ | ||
<TextField.Submit | ||
type="submit" | ||
disabled={isUpdatePromptPending} | ||
/> | ||
} | ||
maxLength={5000} | ||
/> | ||
</TextField> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
TextField 컴포넌트의 접근성을 개선해야 합니다.
TextField에 label이나 aria-label이 누락되어 있어 스크린 리더 사용자의 접근성이 제한될 수 있습니다.
<TextField variant="white">
+ <TextField.Label className="sr-only">
+ AI 프롬프트 입력
+ </TextField.Label>
<TextField.Input
{...register('prompt')}
value={promptValue}
onChange={(e) => setValue('prompt', e.target.value)}
placeholder="AI에게 요청하여 글 업그레이드하기"
+ aria-label="AI 프롬프트 입력"
sumbitButton={
<TextField.Submit
type="submit"
disabled={isUpdatePromptPending}
/>
}
maxLength={5000}
/>
</TextField>
{getItemsByStatus(POST_STATUS.GENERATED).map((item) => ( | ||
<> | ||
<DndController.Item | ||
key={item.id} | ||
id={item.id} | ||
summary={item.summary} | ||
updatedAt={item.updatedAt} | ||
onRemove={() => handleDeletePost(item.id)} | ||
onModify={() => handleModify(item.id)} | ||
isLoading={item.uploadTime === SKELETON_STATUS} | ||
/> | ||
</> | ||
))} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
key prop이 Fragment에 잘못 지정되어 있습니다.
Fragment 대신 DndController.Item에 key prop을 지정해야 합니다.
{getItemsByStatus(POST_STATUS.GENERATED).map((item) => (
- <>
- <DndController.Item
- key={item.id}
- id={item.id}
- summary={item.summary}
- updatedAt={item.updatedAt}
- onRemove={() => handleDeletePost(item.id)}
- onModify={() => handleModify(item.id)}
- isLoading={item.uploadTime === SKELETON_STATUS}
- />
- </>
+ <DndController.Item
+ key={item.id}
+ id={item.id}
+ summary={item.summary}
+ updatedAt={item.updatedAt}
+ onRemove={() => handleDeletePost(item.id)}
+ onModify={() => handleModify(item.id)}
+ isLoading={item.uploadTime === SKELETON_STATUS}
+ />
))}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
{getItemsByStatus(POST_STATUS.GENERATED).map((item) => ( | |
<> | |
<DndController.Item | |
key={item.id} | |
id={item.id} | |
summary={item.summary} | |
updatedAt={item.updatedAt} | |
onRemove={() => handleDeletePost(item.id)} | |
onModify={() => handleModify(item.id)} | |
isLoading={item.uploadTime === SKELETON_STATUS} | |
/> | |
</> | |
))} | |
{getItemsByStatus(POST_STATUS.GENERATED).map((item) => ( | |
<DndController.Item | |
key={item.id} | |
id={item.id} | |
summary={item.summary} | |
updatedAt={item.updatedAt} | |
onRemove={() => handleDeletePost(item.id)} | |
onModify={() => handleModify(item.id)} | |
isLoading={item.uploadTime === SKELETON_STATUS} | |
/> | |
))} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🔭 Outside diff range comments (1)
apps/web/src/components/common/DNDController/hooks/useDragAndDrop.ts (1)
40-112
: 예외 처리 강화가 필요합니다.드래그 앤 드롭 처리 중 발생할 수 있는 예외 상황(예: 유효하지 않은 상태 전환, 잘못된 인덱스 등)에 대한 처리가 부족합니다. try-catch 블록을 추가하고 사용자에게 적절한 피드백을 제공하는 것이 좋습니다.
const handleDragOver = (event: DragOverEvent) => { + try { const { active, over } = event; if (!over) return; // ... existing code ... + } catch (error) { + console.error('드래그 앤 드롭 처리 중 오류 발생:', error); + // 사용자에게 오류 알림 + } };
🧹 Nitpick comments (4)
apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/Edit.tsx (2)
31-40
: 성능 최적화를 위해 useMemo 사용을 고려하세요.
hasReadyToUploadPosts
와isGenerating
상태 체크는 posts가 변경될 때마다 재계산됩니다. useMemo를 사용하여 불필요한 재계산을 방지할 수 있습니다.- const hasReadyToUploadPosts = posts.data.posts.some( - (post) => post.status === POST_STATUS.READY_TO_UPLOAD - ); - - const isGenerating = posts.data.posts.some( - (post) => post.uploadTime === SKELETON_STATUS - ); + const hasReadyToUploadPosts = useMemo( + () => posts.data.posts.some( + (post) => post.status === POST_STATUS.READY_TO_UPLOAD + ), + [posts.data.posts] + ); + + const isGenerating = useMemo( + () => posts.data.posts.some( + (post) => post.uploadTime === SKELETON_STATUS + ), + [posts.data.posts] + );
70-70
: key prop 최적화가 필요합니다.posts ID를 join하는 방식은 불필요한 문자열 연산을 발생시킬 수 있습니다. 대신 posts 배열의 길이나 마지막 수정 시간을 key로 사용하는 것이 더 효율적일 수 있습니다.
- key={posts.data.posts.map((p) => p.id).join(',')} + key={`${posts.data.posts.length}-${posts.data.posts[posts.data.posts.length - 1]?.id ?? ''}`}apps/web/src/components/common/DNDController/hooks/useDragAndDrop.ts (2)
13-24
: 타입 안전성 개선이 필요합니다.
updateDisplayOrders
함수에서 반환되는 배열의 타입이 명시적으로 선언되어 있지 않습니다. 타입 안전성을 위해 반환 타입을 명시하는 것이 좋습니다.-function updateDisplayOrders(items: Post[]) { +function updateDisplayOrders(items: Post[]): Post[] {
114-181
: 성능 최적화가 필요합니다.
handleDragEnd
함수에서 여러 번의 배열 순회와 상태 업데이트가 발생합니다. 이는 큰 데이터셋에서 성능 저하를 일으킬 수 있습니다.다음과 같은 최적화를 고려해보세요:
- 배열 순회 최소화
- 불변성을 유지하면서 효율적인 업데이트 수행
const handleDragEnd = (event: DragEndEvent) => { + const updatedItems = new Map(items.map(item => [item.id, { ...item }])); // ... existing code ... - sourceItems.forEach((item, index) => { - item.displayOrder = index + 1; - }); + let displayOrder = 1; + for (const itemId of sourceItems) { + updatedItems.get(itemId).displayOrder = displayOrder++; + } // ... rest of the code using updatedItems map };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/Edit.tsx
(3 hunks)apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/_components/EditContent/EditContent.tsx
(1 hunks)apps/web/src/components/common/DNDController/context/DndContext.tsx
(4 hunks)apps/web/src/components/common/DNDController/hooks/useDragAndDrop.ts
(4 hunks)apps/web/src/store/mutation/useCreateMorePostsMutation.ts
(1 hunks)apps/web/src/store/mutation/useCreatePostsMutation.ts
(1 hunks)apps/web/src/types/post.ts
(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
- apps/web/src/components/common/DNDController/context/DndContext.tsx
- apps/web/src/store/mutation/useCreateMorePostsMutation.ts
- apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/_components/EditContent/EditContent.tsx
- apps/web/src/types/post.ts
🔇 Additional comments (4)
apps/web/src/store/mutation/useCreatePostsMutation.ts (2)
6-6
: 타입 재사용을 위한 import 추가가 잘 되었습니다.공통 타입을 재사용하여 타입 일관성을 유지하는 것이 좋은 접근 방식입니다.
12-12
: 응답 타입 구조가 적절하게 단순화되었습니다.
CreatedPost
타입을 재사용하여 응답 타입을 정의함으로써 코드의 일관성과 유지보수성이 향상되었습니다.다만, 이 변경으로 인한 영향도를 확인하기 위해 다음 스크립트를 실행해보시기 바랍니다:
✅ Verification successful
🏁 Script executed:
#!/bin/bash # Description: CreatedPost 타입을 사용하는 다른 파일들을 검색하여 호환성 확인 # CreatedPost 타입 사용처 검색 rg "CreatedPost" -t typescriptLength of output: 65
아래와 같이 확장자 기반 검색을 수행하는 스크립트를 추가 요청드립니다. 이전 명령어에서 “typescript” 파일 타입이 인식되지 않아 결과를 얻지 못한 것으로 보입니다.
🏁 Script executed:
#!/bin/bash # CreatedPost 타입 사용처 재검증을 위한 명령어 (TypeScript 관련 확장자 지원) rg "CreatedPost" -g "*.ts" -g "*.tsx"Length of output: 527
응답 타입 단순화 및 재사용 확인
리뷰 코멘트에서 언급한 대로, 코드베이스 내에서 CreatedPost 타입이 올바르게 정의되고 재사용되고 있으며, 해당 타입을 이용해 MutationCreatePostsResponse가 단순화되어 유지보수성이 향상되었습니다.
- apps/web/src/types/post.ts에서 CreatedPost 타입 정의
- apps/web/src/store/mutation/useCreatePostsMutation.ts와 useCreateMorePostsMutation.ts에서 CreatedPost 타입 재사용
apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/Edit.tsx (2)
18-25
: 로딩 및 에러 상태 처리가 여전히 누락되어 있습니다.데이터 페칭 시 사용자 경험 향상을 위해 로딩 상태와 에러 상태 처리가 필요합니다.
69-90
: 업데이트 요청의 경쟁 상태를 방지해야 합니다.드래그 앤 드롭 이벤트로 인한 연속적인 업데이트 요청이 발생할 수 있습니다.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🔭 Outside diff range comments (1)
apps/web/src/components/common/DNDController/hooks/useDragAndDrop.ts (1)
40-118
: 예외 처리를 강화하면 좋겠습니다.드래그 앤 드롭 처리 중 발생할 수 있는 예외 상황에 대한 처리가 부족합니다.
다음과 같이 예외 처리를 추가하는 것을 추천드립니다:
const handleDragOver = (event: DragOverEvent) => { const { active, over } = event; - if (!over) return; + if (!over) { + console.warn('드래그 오버 대상이 없습니다.'); + return; + } const draggedItemId = Number(active.id); const draggedItem = items.find((item) => item.id === draggedItemId); - if (!draggedItem) return; + if (!draggedItem) { + console.error('드래그 중인 아이템을 찾을 수 없습니다:', draggedItemId); + return; + }
🧹 Nitpick comments (8)
apps/web/src/types/post.ts (3)
27-28
: 새로 추가된 속성에 대한 문서화가 필요합니다.
displayOrder
와isLoading
속성의 용도와 사용 시나리오에 대한 JSDoc 주석을 추가하면 좋을 것 같습니다.예시:
export interface Post { + /** 게시물의 표시 순서를 지정합니다. */ displayOrder?: number; + /** API 작업 중 로딩 상태를 표시합니다. */ isLoading?: boolean; }
41-56
:NewsCategory
타입의 분리를 고려해보세요.
NewsCategory
와 같은 큰 열거형 타입은 별도의 파일로 분리하는 것이 코드 관리와 유지보수에 도움이 될 것 같습니다. 향후 카테고리가 추가되거나 변경될 때 더 쉽게 관리할 수 있습니다.+ // news-category.ts + export type NewsCategory = + | 'INVEST' + | 'STOCK' + // ... other categories + | 'ENGINEER';
60-70
: 타입 검증 유틸리티 함수 추가를 제안드립니다.
PostGroup
인터페이스에 여러 열거형 타입들이 사용되고 있습니다. 런타임에서 이러한 값들의 유효성을 검증하기 위한 유틸리티 함수를 추가하면 좋을 것 같습니다.예시:
export const isPurpose = (value: unknown): value is Purpose => { return ['INFORMATION', 'OPINION', 'HUMOR', 'MARKETING'].includes(value as Purpose); }; export const isReference = (value: unknown): value is Reference => { return ['NONE', 'NEWS', 'IMAGE'].includes(value as Reference); };apps/web/src/components/common/DNDController/hooks/useDragAndDrop.ts (3)
13-24
: updateDisplayOrders 함수의 성능을 개선할 수 있습니다.현재 구현은 정확하지만, 불필요한 재계산을 방지하기 위해 메모이제이션을 고려해볼 수 있습니다.
다음과 같이 useMemo를 활용하여 성능을 개선할 수 있습니다:
+import { useState, useEffect, useMemo } from 'react'; function updateDisplayOrders(items: Post[]) { - const itemsByStatus = createItemsByStatus(items); + const itemsByStatus = useMemo( + () => createItemsByStatus(items), + [items] + ); Object.values(itemsByStatus).forEach((statusItems) => { statusItems.sort((a, b) => (a.displayOrder || 0) - (b.displayOrder || 0)); statusItems.forEach((item, index) => { item.displayOrder = index + 1; }); }); return Object.values(itemsByStatus).flat(); }
34-38
: getItemsByStatus 함수의 결과를 캐싱하면 좋겠습니다.현재 구현은 매 호출마다 필터링과 정렬을 수행합니다. 성능 최적화를 위해 메모이제이션을 추천드립니다.
다음과 같이 useMemo를 활용하여 개선할 수 있습니다:
const getItemsByStatus = (status: Post['status']) => { - return items - .filter((item) => item.status === status) - .sort((a, b) => (a.displayOrder || 0) - (b.displayOrder || 0)); + return useMemo(() => { + return items + .filter((item) => item.status === status) + .sort((a, b) => (a.displayOrder || 0) - (b.displayOrder || 0)); + }, [items, status]); };
120-187
: 코드 구조를 개선하면 좋겠습니다.handleDragEnd 함수의 로직이 다소 복잡합니다. 가독성과 유지보수성을 위해 로직을 분리하는 것을 추천드립니다.
다음과 같이 로직을 분리할 수 있습니다:
const handleStatusChange = (draggedItem: Post, targetStatus: Post['status']) => { setItems((prev) => { const itemsByStatus = createItemsByStatus(prev); const sourceItems = itemsByStatus[draggedItem.status].filter( (item) => item.id !== draggedItem.id ); const targetItems = itemsByStatus[targetStatus] || []; const updatedItem = { ...draggedItem, status: targetStatus }; targetItems.push(updatedItem); itemsByStatus[draggedItem.status] = sourceItems; itemsByStatus[targetStatus] = targetItems; const newItems = updateDisplayOrders(Object.values(itemsByStatus).flat()); onDragEnd?.(newItems); return newItems; }); }; const handleReorder = (draggedItem: Post, overId: number) => { setItems((prev) => { const itemsByStatus = createItemsByStatus(prev); const statusItems = itemsByStatus[draggedItem.status]; const oldIndex = statusItems.findIndex((item) => item.id === draggedItem.id); const newIndex = statusItems.findIndex((item) => item.id === overId); itemsByStatus[draggedItem.status] = arrayMove(statusItems, oldIndex, newIndex); const newItems = updateDisplayOrders(Object.values(itemsByStatus).flat()); onDragEnd?.(newItems); return newItems; }); };apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/Edit.tsx (2)
30-32
: 메모이제이션을 통한 성능 최적화가 필요합니다.
hasReadyToUploadPosts
계산은 posts가 변경될 때마다 재실행됩니다.useMemo
를 사용하여 불필요한 재계산을 방지하세요.- const hasReadyToUploadPosts = posts.data.posts.some( - (post) => post.status === POST_STATUS.READY_TO_UPLOAD - ); + const hasReadyToUploadPosts = useMemo( + () => posts.data.posts.some( + (post) => post.status === POST_STATUS.READY_TO_UPLOAD + ), + [posts.data.posts] + );
61-61
: key 생성 로직 최적화가 필요합니다.현재 key 생성 방식은 불필요하게 복잡합니다. 더 간단한 방식으로 개선할 수 있습니다.
- key={posts.data.posts.map((p) => p.id).join(',')} + key={posts.data.posts.length}
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/Edit.tsx
(2 hunks)apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/_components/EditContent/EditContent.tsx
(1 hunks)apps/web/src/components/common/DNDController/hooks/useDragAndDrop.ts
(4 hunks)apps/web/src/types/post.ts
(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/_components/EditContent/EditContent.tsx
🔇 Additional comments (5)
apps/web/src/types/post.ts (1)
7-16
: 타입 정의가 잘 구현되었습니다!
POST_STATUS
상수와PostStatus
타입이 타입 안정성을 보장하는 방식으로 잘 구현되었습니다.as const
를 사용하여 리터럴 타입을 보존하고,keyof typeof
를 통해 타입을 추출하는 방식이 적절합니다.apps/web/src/components/common/DNDController/hooks/useDragAndDrop.ts (1)
10-10
: onDragEnd 콜백 시그니처가 개선되었습니다.드래그 앤 드롭 작업 후 업데이트된 아이템 목록을 전달하도록 변경되어 상태 관리가 더 명확해졌습니다.
apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/Edit.tsx (3)
17-24
: 로딩 및 에러 상태 처리가 여전히 누락되어 있습니다.데이터 페칭 시 사용자 경험 향상을 위해 로딩 상태와 에러 상태 처리가 필요합니다.
다음과 같이 개선하세요:
- const { data: posts } = useGetAllPostsQuery({ + const { data: posts, isLoading, error } = useGetAllPostsQuery({ agentId, postGroupId, }); const { mutate: updatePosts } = useUpdatePostsMutation({ agentId, postGroupId, }); + + if (isLoading) return <LoadingSpinner />; + if (error) return <ErrorComponent message={error.message} />; + if (!posts?.data?.posts) return null;
60-74
: 드래그 앤 드롭 업데이트 최적화가 필요합니다.연속적인 드래그 앤 드롭으로 인한 불필요한 서버 요청을 방지하기 위해 디바운스 처리가 필요합니다.
다음과 같이 개선하세요:
+import { debounce } from 'lodash'; + <DndController key={posts.data.posts.map((p) => p.id).join(',')} initialItems={posts.data.posts} - onDragEnd={(updatedItems) => { + onDragEnd={debounce((updatedItems) => { const updatePayload = { posts: updatedItems.map((item) => ({ postId: item.id, status: item.status, displayOrder: item.displayOrder, uploadTime: item.uploadTime, })), }; updatePosts(updatePayload); - }} + }, 300)} >
49-51
: 라우팅 로직에 에러 처리가 필요합니다.라우팅 실패 시 사용자에게 적절한 피드백을 제공해야 합니다.
- onClick={() => - router.push(`/edit/${agentId}/${postGroupId}/schedule`) - } + onClick={async () => { + try { + await router.push(`/edit/${agentId}/${postGroupId}/schedule`); + } catch (error) { + // 에러 처리 로직 추가 (예: 토스트 메시지 표시) + console.error('페이지 이동 중 오류가 발생했습니다:', error); + } + }}✅ Verification successful
라우팅 에러 처리 추가 필요
현재
router.push
호출은 기본 코드에서 에러 처리가 되어 있지 않으므로, 에러 발생 시 사용자에게 알림(예: 토스트 메시지)을 제공할 수 있도록 try/catch 블록을 사용한 에러 처리 로직을 추가하는 것이 좋습니다.
- 파일: apps/web/src/app/(prompt)/edit/[agentId]/[postGroupId]/Edit.tsx (라인 49-51)
- 개선안: onClick 핸들러 내부에서 router.push 호출을 async/await와 try/catch 구문으로 감싸, 에러 발생 시 적절한 피드백을 구현
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
너무 고생하셨습니다 ㅠㅠ!! 오늘 UT 이슈로 어프루브 남깁니다...!! 빌드 에러 안 나면 바로 머지하시면 될 것 같아요!
관련 이슈
close: #110
변경 사항
결과 수정 페이지를 위한 기능 및 api 연동을 모두 완료했어요. 자잘한 버그도 함께 수정했어요.
2025-02-07.6.23.11.mov
레퍼런스
Summary by CodeRabbit