diff --git a/src/helper/commit.ts b/src/helper/commit.ts index 01db36a..e7d838d 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 e8d3bc3..10a535a 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";