metal-orm 1.0.36 → 1.0.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "metal-orm",
3
- "version": "1.0.36",
3
+ "version": "1.0.38",
4
4
  "type": "module",
5
5
  "types": "./dist/index.d.ts",
6
6
  "engines": {
@@ -185,24 +185,49 @@ export class OrmSession<E extends DomainEvent = OrmDomainEvent> implements Entit
185
185
  await this.unitOfWork.flush();
186
186
  }
187
187
 
188
- async commit(): Promise<void> {
189
- await runInTransaction(this.executor, async () => {
190
- for (const interceptor of this.interceptors) {
191
- await interceptor.beforeFlush?.(this);
192
- }
188
+ private async flushWithHooks(): Promise<void> {
189
+ for (const interceptor of this.interceptors) {
190
+ await interceptor.beforeFlush?.(this);
191
+ }
192
+
193
+ await this.unitOfWork.flush();
194
+ await this.relationChanges.process();
195
+ await this.unitOfWork.flush();
193
196
 
194
- await this.unitOfWork.flush();
195
- await this.relationChanges.process();
196
- await this.unitOfWork.flush();
197
+ for (const interceptor of this.interceptors) {
198
+ await interceptor.afterFlush?.(this);
199
+ }
200
+ }
197
201
 
198
- for (const interceptor of this.interceptors) {
199
- await interceptor.afterFlush?.(this);
200
- }
202
+ async commit(): Promise<void> {
203
+ await runInTransaction(this.executor, async () => {
204
+ await this.flushWithHooks();
201
205
  });
202
206
 
203
207
  await this.domainEvents.dispatch(this.unitOfWork.getTracked(), this);
204
208
  }
205
209
 
210
+ async transaction<T>(fn: (session: OrmSession<E>) => Promise<T>): Promise<T> {
211
+ // If the executor can't do transactions, just run and commit once.
212
+ if (!this.executor.beginTransaction) {
213
+ const result = await fn(this);
214
+ await this.commit();
215
+ return result;
216
+ }
217
+
218
+ await this.executor.beginTransaction();
219
+ try {
220
+ const result = await fn(this);
221
+ await this.flushWithHooks();
222
+ await this.executor.commitTransaction?.();
223
+ await this.domainEvents.dispatch(this.unitOfWork.getTracked(), this);
224
+ return result;
225
+ } catch (err) {
226
+ await this.rollback();
227
+ throw err;
228
+ }
229
+ }
230
+
206
231
  async rollback(): Promise<void> {
207
232
  await this.executor.rollbackTransaction?.();
208
233
  this.unitOfWork.reset();