migrate to dedicated api for chat endpoints#1602
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
📝 WalkthroughWalkthroughThis pull request removes the local Next.js API proxy layer for chat operations, replacing it with direct client-side calls to an external API using bearer token authentication. The changes eliminate three API route handlers, the proxy utility, and refactor the chat creation hook to call the external endpoint directly. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ❌ 1❌ Failed checks (1 inconclusive)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
hooks/useCreateChat.tsx (1)
69-76: Direct API call with bearer auth looks solid.The migration from the local proxy to the external API is well-implemented and consistent with other callers in the codebase (
getConversations,updateChat). Bearer token authentication is the appropriate pattern here.One consideration: network requests without timeouts can hang indefinitely if the external service is unresponsive. This could leave the user waiting without feedback.
💡 Optional: Add AbortController timeout for resilience
const createChat = async () => { try { + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 30000); + // Extract first message from optimistic memories ... const response = await fetch(`${NEW_API_BASE_URL}/api/chats`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${accessToken}`, }, body: JSON.stringify(requestBody), + signal: controller.signal, }); + clearTimeout(timeoutId);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@hooks/useCreateChat.tsx` around lines 69 - 76, The fetch call in the useCreateChat hook can hang indefinitely; wrap the POST request to `${NEW_API_BASE_URL}/api/chats` with an AbortController: create the controller, start a timeout (e.g., 10s) that calls controller.abort(), pass controller.signal into the fetch options, and clear the timeout after fetch completes (or in a finally block) to avoid leaks; reference the existing variables NEW_API_BASE_URL, accessToken, requestBody and the fetch invocation inside the hook when applying the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@hooks/useCreateChat.tsx`:
- Around line 78-89: The code parses response.json() into CreateChatResponse
without checking HTTP status, which can cause failures for 4xx/5xx responses;
update the response handling in the async creator (where response is used along
with setDisplayName and refetchConversations) to first check response.ok and, if
false, attempt to read a safe error body (or at least log response.status and
statusText) and handle/throw accordingly, only calling response.json() and
casting to CreateChatResponse when response.ok is true so success path
(setDisplayName(...), await refetchConversations()) only runs for valid
responses.
---
Nitpick comments:
In `@hooks/useCreateChat.tsx`:
- Around line 69-76: The fetch call in the useCreateChat hook can hang
indefinitely; wrap the POST request to `${NEW_API_BASE_URL}/api/chats` with an
AbortController: create the controller, start a timeout (e.g., 10s) that calls
controller.abort(), pass controller.signal into the fetch options, and clear the
timeout after fetch completes (or in a finally block) to avoid leaks; reference
the existing variables NEW_API_BASE_URL, accessToken, requestBody and the fetch
invocation inside the hook when applying the change.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 13355a9b-6f88-4644-8753-62817c3fef81
⛔ Files ignored due to path filters (2)
lib/chat/__tests__/proxyToApiChat.test.tsis excluded by!**/*.test.*and included bylib/**types/Chat.tsxis excluded by none and included by none
📒 Files selected for processing (5)
app/api/chat/create/route.tsapp/api/chat/generate/route.tsapp/api/chat/route.tshooks/useCreateChat.tsxlib/chat/proxyToApiChat.ts
💤 Files with no reviewable changes (4)
- app/api/chat/route.ts
- app/api/chat/generate/route.ts
- app/api/chat/create/route.ts
- lib/chat/proxyToApiChat.ts
| const data: CreateChatResponse = await response.json(); | ||
|
|
||
| if (data.success && data.room) { | ||
| if (data.status === "success" && data.chat) { | ||
| // Update display name with the room topic | ||
| setDisplayName(data.room.topic); | ||
| setDisplayName(data.chat.topic || ""); | ||
|
|
||
| // Remove optimistic flag from memory and treat it as a normal memory. | ||
| // It will re-enable 3 dots on the chat item. | ||
| await refetchConversations(); | ||
| } else { | ||
| console.error("Failed to create chat:", data.error); | ||
| console.error("Failed to create chat:", data.error || data.message); | ||
| } |
There was a problem hiding this comment.
Missing HTTP status check before parsing response.
The code parses response.json() directly without first checking response.ok. If the external API returns a 4xx/5xx error, the JSON structure might differ from CreateChatResponse, or the parse could fail entirely if the response isn't valid JSON.
🛡️ Proposed fix to add status check
const response = await fetch(`${NEW_API_BASE_URL}/api/chats`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify(requestBody),
});
+ if (!response.ok) {
+ console.error("Failed to create chat: HTTP", response.status);
+ return;
+ }
+
const data: CreateChatResponse = await response.json();🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@hooks/useCreateChat.tsx` around lines 78 - 89, The code parses
response.json() into CreateChatResponse without checking HTTP status, which can
cause failures for 4xx/5xx responses; update the response handling in the async
creator (where response is used along with setDisplayName and
refetchConversations) to first check response.ok and, if false, attempt to read
a safe error body (or at least log response.status and statusText) and
handle/throw accordingly, only calling response.json() and casting to
CreateChatResponse when response.ok is true so success path
(setDisplayName(...), await refetchConversations()) only runs for valid
responses.
Summary by CodeRabbit
Release Notes