Skip to content

Commit

Permalink
Enhancement: Avoid using MongoTransaction for individual commits, dis…
Browse files Browse the repository at this point in the history
…allow 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.
  • Loading branch information
ChyzhykTech committed Feb 13, 2024
1 parent 7b4d680 commit ed4ab28
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions src/helper/commit.ts
Original file line number Diff line number Diff line change
@@ -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<IJournal[]> {
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;
}

0 comments on commit ed4ab28

Please sign in to comment.