Skip to content

Commit

Permalink
Implement Multi-Entry Transaction Commit Functionality
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ChyzhykTech committed Feb 10, 2024
1 parent 90270be commit 0e580bb
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 15 deletions.
23 changes: 8 additions & 15 deletions src/helper/commit.ts
Original file line number Diff line number Diff line change
@@ -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<IJournal[]> {
let journals: IJournal[] = [];
await mongoTransaction(async session => {
journals = await Promise.all(entries.map(entry => entry.commit({ session })));
});
return journals;
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down

0 comments on commit 0e580bb

Please sign in to comment.