File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ import { createClient } from '@supabase/supabase-js' ;
2+ import dotenv from 'dotenv' ;
3+
4+ dotenv . config ( ) ;
5+ const supabase = createClient ( process . env . SUPABASE_URL , process . env . SUPABASE_KEY ) ;
6+
7+
8+ export async function getOrCreateChatSession ( req , res ) {
9+ try {
10+ const { userId, classroomId } = req . body ;
11+
12+ if ( ! userId || ! classroomId ) {
13+ return res . status ( 400 ) . json ( { error : "Missing required fields" } ) ;
14+ }
15+
16+ let { data, error } = await supabase
17+ . from ( 'chat_sessions' )
18+ . select ( 'session_id' )
19+ . eq ( 'user_id' , userId )
20+ . eq ( 'classroom_id' , classroomId )
21+ . single ( ) ;
22+
23+ if ( error && error . code !== 'PGRST116' ) {
24+ console . error ( "Error fetching session:" , error ) ;
25+ return res . status ( 500 ) . json ( { error : "Failed to fetch session" } ) ;
26+ }
27+
28+ if ( ! data ) {
29+ const { data : newSession , error : newSessionError } = await supabase
30+ . from ( 'chat_sessions' )
31+ . insert ( { user_id : userId , classroom_id : classroomId } )
32+ . select ( )
33+ . single ( ) ;
34+
35+ if ( newSessionError ) {
36+ console . error ( "Error creating session:" , newSessionError ) ;
37+ return res . status ( 500 ) . json ( { error : "Failed to create session" } ) ;
38+ }
39+ data = newSession ;
40+ }
41+
42+ return res . json ( data ) ;
43+ } catch ( error ) {
44+ console . error ( "Unexpected error:" , error ) ;
45+ return res . status ( 500 ) . json ( { error : "Internal server error" } ) ;
46+ }
47+ }
You can’t perform that action at this time.
0 commit comments