Skip to content

Commit

Permalink
Merge pull request #495 from Ungate-Ai/main
Browse files Browse the repository at this point in the history
fix: Gracefully Handle Add Participants Unique Constraint Error in Postgres
  • Loading branch information
ponderingdemocritus authored Nov 22, 2024
2 parents 5ea1551 + 2f06f15 commit 68a4dcd
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions packages/adapter-postgres/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -729,15 +729,34 @@ export class PostgresDatabaseAdapter
async addParticipant(userId: UUID, roomId: UUID): Promise<boolean> {
const client = await this.pool.connect();
try {
// Check if the participant already exists
const existingParticipant = await client.query(
`SELECT * FROM participants WHERE "userId" = $1 AND "roomId" = $2`,
[userId, roomId]
);

if (existingParticipant.rows.length > 0) {
console.log(`Participant with userId ${userId} already exists in room ${roomId}.`);
return; // Exit early if the participant already exists
}

// Proceed to add the participant if they do not exist
await client.query(
`INSERT INTO participants (id, "userId", "roomId")
VALUES ($1, $2, $3)`,
[v4(), userId, roomId]
);
return true;
} catch (error) {
console.log("Error adding participant", error);
return false;
// This is to prevent duplicate participant error in case of a race condition
// Handle unique constraint violation error (code 23505)
if (error.code === '23505') {
console.warn(`Participant with userId ${userId} already exists in room ${roomId}.`); // Optionally, you can log this or handle it differently
} else {
// Handle other errors
console.error('Error adding participant:', error);
return false;
}
} finally {
client.release();
}
Expand Down

0 comments on commit 68a4dcd

Please sign in to comment.