Skip to content

Commit 68a4dcd

Browse files
Merge pull request #495 from Ungate-Ai/main
fix: Gracefully Handle Add Participants Unique Constraint Error in Postgres
2 parents 5ea1551 + 2f06f15 commit 68a4dcd

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

packages/adapter-postgres/src/index.ts

+21-2
Original file line numberDiff line numberDiff line change
@@ -729,15 +729,34 @@ export class PostgresDatabaseAdapter
729729
async addParticipant(userId: UUID, roomId: UUID): Promise<boolean> {
730730
const client = await this.pool.connect();
731731
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
732744
await client.query(
733745
`INSERT INTO participants (id, "userId", "roomId")
734746
VALUES ($1, $2, $3)`,
735747
[v4(), userId, roomId]
736748
);
737749
return true;
738750
} 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+
}
741760
} finally {
742761
client.release();
743762
}

0 commit comments

Comments
 (0)