Skip to content

Commit

Permalink
fix: split operations to prevent race condition
Browse files Browse the repository at this point in the history
  • Loading branch information
ricardogarim committed Sep 26, 2024
1 parent 47c584c commit b3db943
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions apps/meteor/server/models/raw/BaseRaw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,33 +318,33 @@ export abstract class BaseRaw<

async findOneAndDelete(filter: Filter<T>, options?: FindOneAndDeleteOptions): Promise<ModifyResult<T>> {
if (!this.trash) {
if (options) {
return this.col.findOneAndDelete(filter, options);
}
return this.col.findOneAndDelete(filter);
return this.col.findOneAndDelete(filter, options || {});
}

const result = await this.col.findOneAndDelete(filter);

const { value: doc } = result;
const doc = await this.col.findOne(filter);
if (!doc) {
return result;
return { ok: 1, value: null };
}

const { _id, ...record } = doc;

const trash: TDeleted = {
...record,
_deletedAt: new Date(),
__collection__: this.name,
} as unknown as TDeleted;

// since the operation is not atomic, we need to make sure that the record is not already deleted/inserted
await this.trash?.updateOne({ _id } as Filter<TDeleted>, { $set: trash } as UpdateFilter<TDeleted>, {
upsert: true,
});

return result;
try {
await this.col.deleteOne({ _id } as Filter<T>);
} catch (e) {
await this.trash?.deleteOne({ _id } as Filter<TDeleted>);
throw e;
}

return { ok: 1, value: doc };
}

async deleteMany(filter: Filter<T>, options?: DeleteOptions & { onTrash?: (record: ResultFields<T, C>) => void }): Promise<DeleteResult> {
Expand Down

0 comments on commit b3db943

Please sign in to comment.