Refactor presence upsert logic to handle duplicate entries. Added exception handling for MongoDB adapter to update existing documents instead of creating new ones when presenceId mismatches occur.

This commit is contained in:
ArnabChatterjee20k
2026-04-16 18:14:13 +05:30
parent a480d8ed73
commit 2ef62b309e
2 changed files with 12 additions and 4 deletions
+1 -2
View File
@@ -1235,8 +1235,7 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re
// if presenceId differs then it will create a new document and not update the existing one
// TODO: send better error message telling about the presenceId mismatch
$existingPresence = $database->findOne('presenceLogs', [Query::equal('userId', [$userId])]);
$presenceDocument->setAttribute('$id', $existingPresence->getId());
$presence = $database->upsertDocument('presenceLogs', $presenceDocument);
$presence = $database->updateDocument('presenceLogs', $existingPresence->getId(), $presenceDocument);
}
$presence->removeAttribute('hostname');
@@ -13,6 +13,7 @@ use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\DateTime;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\Datetime as DatetimeValidator;
use Utopia\Database\Validator\Permissions;
@@ -125,8 +126,16 @@ class Upsert extends PresenceAction
if ($presenceId !== 'unique()') {
$presenceDocument->setAttribute('$id', $presenceId);
}
$presence = $dbForProject->upsertDocument('presenceLogs', $presenceDocument);
try {
$presence = $dbForProject->upsertDocument('presenceLogs', $presenceDocument);
} catch (Duplicate $th) {
// will be triggerd in case of mongodb adapter everytime as $id needs to be same as well here
// in mongodb , upsert works on basis of set and unset by comparing the document with the existing one
// if presenceId differs then it will create a new document and not update the existing one
// TODO: send better error message telling about the presenceId mismatch
$existingPresence = $dbForProject->findOne('presenceLogs', [Query::equal('userId', [$userId])]);
$presence = $dbForProject->updateDocument('presenceLogs', $existingPresence->getId(), $presenceDocument);
}
$queueForEvents->setParam('presenceId', $presence->getId());
$response->dynamic($presence, Response::MODEL_PRESENCE);