File tree 1 file changed +21
-2
lines changed
packages/adapter-postgres/src
1 file changed +21
-2
lines changed Original file line number Diff line number Diff line change @@ -729,15 +729,34 @@ export class PostgresDatabaseAdapter
729
729
async addParticipant ( userId : UUID , roomId : UUID ) : Promise < boolean > {
730
730
const client = await this . pool . connect ( ) ;
731
731
try {
732
+ // Check if the participant already exists
733
+ const existingParticipant = await client . query (
734
+ `SELECT * FROM participants WHERE "userId" = $1 AND "roomId" = $2` ,
735
+ [ userId , roomId ]
736
+ ) ;
737
+
738
+ if ( existingParticipant . rows . length > 0 ) {
739
+ console . log ( `Participant with userId ${ userId } already exists in room ${ roomId } .` ) ;
740
+ return ; // Exit early if the participant already exists
741
+ }
742
+
743
+ // Proceed to add the participant if they do not exist
732
744
await client . query (
733
745
`INSERT INTO participants (id, "userId", "roomId")
734
746
VALUES ($1, $2, $3)` ,
735
747
[ v4 ( ) , userId , roomId ]
736
748
) ;
737
749
return true ;
738
750
} catch ( error ) {
739
- console . log ( "Error adding participant" , error ) ;
740
- return false ;
751
+ // This is to prevent duplicate participant error in case of a race condition
752
+ // Handle unique constraint violation error (code 23505)
753
+ if ( error . code === '23505' ) {
754
+ console . warn ( `Participant with userId ${ userId } already exists in room ${ roomId } .` ) ; // Optionally, you can log this or handle it differently
755
+ } else {
756
+ // Handle other errors
757
+ console . error ( 'Error adding participant:' , error ) ;
758
+ return false ;
759
+ }
741
760
} finally {
742
761
client . release ( ) ;
743
762
}
You can’t perform that action at this time.
0 commit comments