From ed4ab28f1d5b153c79c5105f46a826aa2d6154d4 Mon Sep 17 00:00:00 2001 From: Serhii Chyzhyk Date: Wed, 14 Feb 2024 10:31:13 +1100 Subject: [PATCH] Enhancement: Avoid using MongoTransaction for individual commits, disallow committing empty entries. This function commits a list of entries to the database using a MongoDB (mongoTransaction helper function) transaction if there are multiple entries provided. It ensures atomicity for multiple commits. However, it does not use a transaction for single commits and prohibits committing empty entries. --- src/helper/commit.ts | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/helper/commit.ts b/src/helper/commit.ts index 4197a9a..61f28d9 100644 --- a/src/helper/commit.ts +++ b/src/helper/commit.ts @@ -1,11 +1,20 @@ -import Entry from "../Entry"; +import { Entry } from "../Entry"; import { mongoTransaction } from "./mongoTransaction"; import { IJournal } from "../models/journal"; +import { MediciError } from "../errors"; export async function commit(...entries: Entry[]): Promise { - let journals: IJournal[] = []; - await mongoTransaction(async (session) => { - journals = await Promise.all(entries.map((entry) => entry.commit({ session }))); - }); - return journals; + if (!entries.length) throw new MediciError("Nothing to commit. At least one entry must be provided."); + + let committedJournals: IJournal[] = []; + + if (entries.length === 1) { + committedJournals.push(await entries[0].commit()); + } else { + await mongoTransaction(async (session) => { + committedJournals = await Promise.all(entries.map((entry) => entry.commit({ session }))); + }); + } + + return committedJournals; }