Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 7
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
Uh oh!
There was an error while loading. Please reload this page.
Changes from all commits
c661b0c9b39f71d75ecea67ebe3a00d2a0e46261c41d684e5File filter
Filter by extension
Conversations
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
| 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 }); | ||
| } | ||
| } |
| 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 }); | ||
| } | ||
| } | ||
| 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 was deleted.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
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