@efesto-cloud/mongodb-database-context
v0.0.4
Published
Usecase type for efesto-cloud
Readme
@efesto-cloud/mongodb-database-context
MongoDB implementation of IDatabaseContext. Wraps a MongoClient and exposes a ClientSession that repositories can use for session-scoped reads/writes inside runWithTransaction.
Installation
pnpm add @efesto-cloud/mongodb-database-context @efesto-cloud/database-context mongodbQuick Start
import { MongoClient } from "mongodb";
import MongoDBContext from "@efesto-cloud/mongodb-database-context/MongoDBContext";
const client = new MongoClient(process.env.MONGO_URL!);
await client.connect();
const db = new MongoDBContext(client);
await db.runWithTransaction(async () => {
await coll.updateOne(
{ _id: id },
{ $set: { … } },
{ session: db.session }, // pass the session to every op
);
});API
interface IMongoDBContext extends IDatabaseContext {
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
db.sessioninto their MongoDB calls — forgetting to do so opts that operation out of the transaction.
