2024-08-14 16:33:40 -04:00
import { db } from "@/lib/db"
import { NextResponse } from "next/server" ;
import fetchUserWithImpersonation from "@/lib/fetch-user-impersonation" ;
2024-08-25 17:35:46 -04:00
import { z } from "zod" ;
const groupIdSchema = z . string ( {
required_error : "Group ID should be available." ,
invalid_type_error : "Group ID must be a string"
} ) . regex ( /^[\w\-\=]{1,32}$/ , "Group ID must contain only letters, numbers, dashes, underscores & equal signs." )
2024-08-14 16:33:40 -04:00
export async function GET ( req : Request ) {
try {
const user = await fetchUserWithImpersonation ( req )
if ( ! user )
2024-08-25 17:35:46 -04:00
return NextResponse . json ( { message : 'Unauthorized.' , error : null , value : null } , { status : 401 } )
2024-08-14 16:33:40 -04:00
const { searchParams } = new URL ( req . url )
const groupId = searchParams . get ( 'groupId' ) as string
2024-08-25 17:35:46 -04:00
if ( groupId ) {
const groupIdValidation = await groupIdSchema . safeParseAsync ( groupId )
if ( ! groupIdValidation . success )
return NextResponse . json ( { message : 'groupId does not meet requirements.' , error : JSON.parse ( groupIdValidation . error [ 'message' ] ) [ 0 ] , value : null } , { status : 400 } )
}
2024-08-14 16:33:40 -04:00
let chatters : { userId : string , groupId : string , chatterId : bigint , chatterLabel : string } [ ]
2024-08-25 17:35:46 -04:00
if ( groupId )
2024-08-14 16:33:40 -04:00
chatters = await db . chatterGroup . findMany ( {
where : {
userId : user.id ,
groupId
}
} )
else
chatters = await db . chatterGroup . findMany ( {
where : {
userId : user.id
}
} )
return NextResponse . json ( chatters . map ( u = > ( { . . . u , chatterId : Number ( u . chatterId ) } ) )
2024-08-25 17:35:46 -04:00
. map ( ( { userId , chatterLabel , . . . attrs } ) = > attrs ) )
2024-08-14 16:33:40 -04:00
} catch ( error ) {
2024-08-25 17:35:46 -04:00
return NextResponse . json ( { message : 'Failed to get groups' , error : error , value : null } , { status : 500 } )
2024-08-14 16:33:40 -04:00
}
}