-
-
Notifications
You must be signed in to change notification settings - Fork 6
feat: Initial Supabase and Drizzle integration for chat backend #194
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
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
c661b0c
feat: Initial Supabase and Drizzle integration for chat backend
google-labs-jules[bot] 9b39f71
feat: Implement Supabase chat backend, core fixes, and initial UI upd…
google-labs-jules[bot] d75ecea
fix: Address build errors and apply critical fixes
google-labs-jules[bot] 67ebe3a
fix: Correct type for initial message in POST /api/chat
google-labs-jules[bot] 00d2a0e
fix: Load chat messages in search page and resolve build error
google-labs-jules[bot] 46261c4
fix build issues
ngoiyaeric 1d684e5
builds add env
ngoiyaeric File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| import { NextResponse, NextRequest } from 'next/server'; | ||
| import { saveChat, createMessage, NewChat, NewMessage } from '@/lib/actions/chat-db'; | ||
| import { getCurrentUserIdOnServer } from '@/lib/auth/get-current-user'; | ||
| // import { generateUUID } from '@/lib/utils'; // Assuming generateUUID is in lib/utils as per PR context - not needed for PKs | ||
|
|
||
| // This is a simplified POST handler. PR #533's version might be more complex, | ||
| // potentially handling streaming AI responses and then saving. | ||
| // For now, this focuses on the database interaction part. | ||
| export async function POST(request: NextRequest) { | ||
| try { | ||
| const userId = await getCurrentUserIdOnServer(); | ||
| if (!userId) { | ||
| return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); | ||
| } | ||
|
|
||
| const body = await request.json(); | ||
|
|
||
| // Example: Distinguish between creating a new chat vs. adding a message to existing chat | ||
| // The actual structure of `body` would depend on client-side implementation. | ||
| // Let's assume a simple case: creating a new chat with an initial message. | ||
| const { title, initialMessageContent, role = 'user' } = body; | ||
|
|
||
| if (!initialMessageContent) { | ||
| return NextResponse.json({ error: 'Initial message content is required' }, { status: 400 }); | ||
| } | ||
|
|
||
| const newChatData: NewChat = { | ||
| // id: generateUUID(), // Drizzle schema now has defaultRandom for UUIDs | ||
| userId: userId, | ||
| title: title || 'New Chat', // Default title if not provided | ||
| // createdAt: new Date(), // Handled by defaultNow() in schema | ||
| visibility: 'private', // Default visibility | ||
| }; | ||
|
|
||
| // Use a transaction if creating chat and first message together | ||
| // For simplicity here, let's assume saveChat handles chat creation and returns ID, then we create a message. | ||
| // A more robust `saveChat` might create the chat and first message in one go. | ||
| // The `saveChat` in chat-db.ts is designed to handle this. | ||
|
|
||
| const firstMessage: Omit<NewMessage, 'chatId'> = { | ||
| // id: generateUUID(), // Drizzle schema now has defaultRandom for UUIDs | ||
| // chatId is omitted as it will be set by saveChat | ||
| userId: userId, | ||
| role: role as NewMessage['role'], // Ensure role type matches schema expectation | ||
| content: initialMessageContent, | ||
| // createdAt: new Date(), // Handled by defaultNow() in schema, not strictly needed here | ||
| }; | ||
|
|
||
| // The saveChat in chat-db.ts is designed to take initial messages. | ||
| const savedChatId = await saveChat(newChatData, [firstMessage]); | ||
|
|
||
| if (!savedChatId) { | ||
| return NextResponse.json({ error: 'Failed to save chat' }, { status: 500 }); | ||
| } | ||
|
|
||
| // Fetch the newly created chat and message to return (optional, but good for client) | ||
| // For now, just return success and the new chat ID. | ||
| return NextResponse.json({ message: 'Chat created successfully', chatId: savedChatId }, { status: 201 }); | ||
|
|
||
| } catch (error) { | ||
| console.error('Error in POST /api/chat:', error); | ||
| let errorMessage = 'Internal Server Error'; | ||
| if (error instanceof Error) { | ||
| errorMessage = error.message; | ||
| } | ||
| return NextResponse.json({ error: errorMessage }, { status: 500 }); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| // Content for app/api/chats/all/route.ts | ||
| import { NextResponse } from 'next/server'; | ||
| import { clearHistory as dbClearHistory } from '@/lib/actions/chat-db'; | ||
| import { getCurrentUserIdOnServer } from '@/lib/auth/get-current-user'; | ||
| import { revalidatePath } from 'next/cache'; // For revalidating after clearing | ||
|
|
||
| export async function DELETE() { | ||
| try { | ||
| const userId = await getCurrentUserIdOnServer(); | ||
| if (!userId) { | ||
| return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); | ||
| } | ||
|
|
||
| const success = await dbClearHistory(userId); | ||
| if (success) { | ||
| revalidatePath('/'); // Revalidate home or relevant pages | ||
| revalidatePath('/search'); // Revalidate search path | ||
| return NextResponse.json({ message: 'History cleared successfully' }, { status: 200 }); | ||
| } else { | ||
| // This case might be redundant if dbClearHistory throws an error on failure, | ||
| // but kept for explicitness if it returns false for "no error but nothing done". | ||
| return NextResponse.json({ error: 'Failed to clear history' }, { status: 500 }); | ||
| } | ||
| } catch (error) { | ||
| console.error('Error clearing history via API:', error); | ||
| let errorMessage = 'Internal Server Error clearing history'; | ||
| if (error instanceof Error && error.message) { | ||
| // Use the error message from dbClearHistory if available (e.g., "User ID is required") | ||
| // This depends on dbClearHistory actually throwing or returning specific error messages. | ||
| // The current dbClearHistory in chat.ts returns {error: ...} which won't be caught here as an Error instance directly. | ||
| // However, the dbClearHistory in chat-db.ts returns boolean. | ||
| // Let's assume if dbClearHistory from chat-db.ts (which returns boolean) fails, it's a generic 500. | ||
| // If it were to throw, that would be caught. | ||
| } | ||
| return NextResponse.json({ error: errorMessage }, { status: 500 }); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| import { NextResponse, NextRequest } from 'next/server'; | ||
| import { getChatsPage } from '@/lib/actions/chat-db'; | ||
| import { getCurrentUserIdOnServer } from '@/lib/auth/get-current-user'; | ||
|
|
||
| export async function GET(request: NextRequest) { | ||
| try { | ||
| const userId = await getCurrentUserIdOnServer(); | ||
| if (!userId) { | ||
| return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); | ||
| } | ||
|
|
||
| const { searchParams } = new URL(request.url); | ||
|
|
||
| const DEFAULT_LIMIT = 20; | ||
| const MAX_LIMIT = 100; | ||
| const DEFAULT_OFFSET = 0; | ||
|
|
||
| let limit = parseInt(searchParams.get('limit') || '', 10); | ||
| if (isNaN(limit) || limit < 1 || limit > MAX_LIMIT) { | ||
| limit = DEFAULT_LIMIT; | ||
| } | ||
|
|
||
| let offset = parseInt(searchParams.get('offset') || '', 10); | ||
| if (isNaN(offset) || offset < 0) { | ||
| offset = DEFAULT_OFFSET; | ||
| } | ||
|
|
||
| const result = await getChatsPage(userId, limit, offset); | ||
| return NextResponse.json(result); | ||
| } catch (error) { | ||
| console.error('Error fetching chats:', error); | ||
| return NextResponse.json({ error: 'Internal Server Error fetching chats' }, { status: 500 }); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
Binary file not shown.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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
Remove dead code and clarify error handling.
The comments and conditional logic in the error handling section appear to be leftover from development and should be cleaned up.
} else { - // This case might be redundant if dbClearHistory throws an error on failure, - // but kept for explicitness if it returns false for "no error but nothing done". return NextResponse.json({ error: 'Failed to clear history' }, { status: 500 }); } } catch (error) { console.error('Error clearing history via API:', error); - let errorMessage = 'Internal Server Error clearing history'; - if (error instanceof Error && error.message) { - // Use the error message from dbClearHistory if available (e.g., "User ID is required") - // This depends on dbClearHistory actually throwing or returning specific error messages. - // The current dbClearHistory in chat.ts returns {error: ...} which won't be caught here as an Error instance directly. - // However, the dbClearHistory in chat-db.ts returns boolean. - // Let's assume if dbClearHistory from chat-db.ts (which returns boolean) fails, it's a generic 500. - // If it were to throw, that would be caught. - } - return NextResponse.json({ error: errorMessage }, { status: 500 }); + return NextResponse.json({ error: 'Internal Server Error clearing history' }, { status: 500 }); }📝 Committable suggestion
🤖 Prompt for AI Agents