From 0e580bbe2465e0cba105fe866c9bb25a0fcff382 Mon Sep 17 00:00:00 2001 From: Serhii Chyzhyk <36365735+ChyzhykTech@users.noreply.github.com> Date: Sat, 10 Feb 2024 23:56:03 +1100 Subject: [PATCH] Implement Multi-Entry Transaction Commit Functionality This commit introduces a new function commit designed to handle the transactional commit of multiple entries within a MongoDB session. Using the mongoTransaction utility, it ensures atomicity and data integrity during the commit process. --- src/helper/commit.ts | 23 ++++++++--------------- src/index.ts | 1 + 2 files changed, 9 insertions(+), 15 deletions(-) diff --git a/src/helper/commit.ts b/src/helper/commit.ts index 01db36a6..e7d838d8 100644 --- a/src/helper/commit.ts +++ b/src/helper/commit.ts @@ -1,18 +1,11 @@ import Entry from "../Entry"; -import { TransactionError } from "../errors"; -import * as mongoose from "mongoose"; +import { mongoTransaction } from "./mongoTransaction"; +import { IJournal } from "../models/journal"; -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(); - } +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; } diff --git a/src/index.ts b/src/index.ts index e8d3bc33..10a535a2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,6 +7,7 @@ export { setLockSchema } from "./models/lock"; export { mongoTransaction } from "./helper/mongoTransaction"; export { initModels } from "./helper/initModels"; export { syncIndexes } from "./helper/syncIndexes"; +export { commit } from "./helper/commit"; export { MediciError } from "./errors/MediciError"; export { BookConstructorError } from "./errors/BookConstructorError";