UNPKG

@mikro-orm/core

Version:

TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.

32 lines (31 loc) 1 kB
import { createAsyncContext } from './AsyncContext.js'; /** Uses `AsyncLocalStorage` to maintain a transaction-scoped EntityManager context across async operations. */ export class TransactionContext { em; static storage = createAsyncContext(); id; constructor(em) { this.em = em; this.id = this.em._id; } /** * Creates new TransactionContext instance and runs the code inside its domain. */ static create(em, next) { const context = new TransactionContext(em); return this.storage.run(context, next); } /** * Returns current TransactionContext (if available). */ static currentTransactionContext() { return this.storage.getStore(); } /** * Returns current EntityManager (if available). */ static getEntityManager(name = 'default') { const context = TransactionContext.currentTransactionContext(); return context?.em.name === name ? context.em : undefined; } }