-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathabstract-use.case.ts
More file actions
50 lines (41 loc) · 1.54 KB
/
abstract-use.case.ts
File metadata and controls
50 lines (41 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { Injectable, Scope } from '@nestjs/common';
import { InTransactionEnum } from '../enums/in-transaction.enum.js';
import { IDatabaseContext } from './database-context.interface.js';
@Injectable({ scope: Scope.REQUEST })
abstract class AbstractUseCase<TInputData = void, TOutputData = void> {
protected _inputData: TInputData;
protected _inTransaction: boolean;
protected abstract _dbContext: IDatabaseContext | null;
public async execute(
inputData: TInputData,
inTransaction: InTransactionEnum = InTransactionEnum.OFF,
): Promise<TOutputData> {
this._inputData = inputData;
this._inTransaction = inTransaction === InTransactionEnum.ON;
try {
if (this._inTransaction) await this.startTransaction();
const result = await this.implementation(inputData);
if (this._inTransaction) await this.commitTransaction();
return result;
} catch (error) {
if (this._inTransaction) await this.rollbackTransaction();
throw error;
} finally {
if (this._inTransaction) await this.releaseQueryRunner();
}
}
protected abstract implementation(inputData: TInputData): Promise<TOutputData> | TOutputData;
private async startTransaction(): Promise<void> {
await this._dbContext.startTransaction();
}
private async commitTransaction(): Promise<void> {
await this._dbContext.commitTransaction();
}
private async rollbackTransaction(): Promise<void> {
await this._dbContext.rollbackTransaction();
}
private async releaseQueryRunner(): Promise<void> {
await this._dbContext.releaseQueryRunner();
}
}
export default AbstractUseCase;