@efesto-cloud/mongodb-unit-of-work
v1.0.0
Published
MongoDB-backed IUnitOfWork for efesto-cloud
Readme
@efesto-cloud/mongodb-unit-of-work
MongoDB implementation of IUnitOfWork. Wraps a MongoClient and exposes a ClientSession that repositories can use for session-scoped reads/writes inside runWithTransaction.
Installation
pnpm add @efesto-cloud/mongodb-unit-of-work @efesto-cloud/unit-of-work mongodbQuick Start
import { MongoClient } from "mongodb";
import MongoDBUnitOfWork from "@efesto-cloud/mongodb-unit-of-work/MongoDBUnitOfWork";
const client = new MongoClient(process.env.MONGO_URL!);
await client.connect();
const uow = new MongoDBUnitOfWork(client);
await uow.runWithTransaction(async () => {
await coll.updateOne(
{ _id: id },
{ $set: { … } },
{ session: uow.session }, // pass the session to every op
);
});API
interface IMongoDBUnitOfWork extends IUnitOfWork {
readonly session: ClientSession | undefined; // active session, if any
readonly sessionOrNull: ClientSession | null;
runWithTransaction<T>(fn: () => Promise<T>): Promise<T>;
}session/sessionOrNull— the currently activeClientSession. Pass it as{ session }to every MongoDB operation so reads/writes participate in the transaction.runWithTransaction(fn)— starts a session and wrapsfninsession.withTransaction. If a transaction is already running (nested call), it reuses the outer one and just invokesfn.
Notes
- The session is started lazily on the first
runWithTransactioncall and ended when the outermost call returns. - Nesting is safe: inner
runWithTransactioncalls run within the outer transaction without starting a new one. - Repositories should always thread
uow.sessioninto their MongoDB calls — forgetting to do so opts that operation out of the transaction.
