From 80b026e91566e6fb76722567af66076cb1cc3a75 Mon Sep 17 00:00:00 2001 From: Serhii Chyzhyk Date: Fri, 9 Feb 2024 23:48:12 +1100 Subject: [PATCH] Implement draft Multi-Entry Transaction Commit Functionality New helper function `commit` to handle the simultaneous transaction commit for multiple entries --- src/helper/commit.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/helper/commit.ts diff --git a/src/helper/commit.ts b/src/helper/commit.ts new file mode 100644 index 0000000..01db36a --- /dev/null +++ b/src/helper/commit.ts @@ -0,0 +1,18 @@ +import Entry from "../Entry"; +import { TransactionError } from "../errors"; +import * as mongoose from "mongoose"; + +export async function commit(...entries: Entry[]) { + const mongooseSession = await mongoose.startSession(); + try { + mongooseSession.startTransaction(); + const journals = await Promise.all(entries.map(entry => entry.commit())); + await mongooseSession.commitTransaction(); + return journals; + } catch (error) { + await mongooseSession.abortTransaction(); + throw new TransactionError(`Failure to commit entries: ${(error as Error).message}`, entries.length,500); + } finally { + await mongooseSession.endSession(); + } +}