1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | class TransactionError extends Error {
|
4 | }
|
5 | exports.TransactionError = TransactionError;
|
6 | class Transaction {
|
7 | constructor() {
|
8 |
|
9 | this.id = Transaction.idInc++;
|
10 |
|
11 | this.began = false;
|
12 | this.finished = false;
|
13 | this.error = null;
|
14 | this.commitListeners = [];
|
15 | this.rollbackListeners = [];
|
16 | this.endListeners = [];
|
17 | }
|
18 | begin() {
|
19 | if (this.began) {
|
20 | throw new TransactionError('Transaction is already started');
|
21 | }
|
22 | this.began = true;
|
23 | }
|
24 | hasBegun() {
|
25 | return this.began;
|
26 | }
|
27 | markError(e) {
|
28 | this.error = e;
|
29 | }
|
30 | addCommitListener(f) {
|
31 | if (!f || !(f instanceof Function)) {
|
32 | throw new TransactionError('Provided input to addCommitListener is not a function');
|
33 | }
|
34 | this.commitListeners.push(f);
|
35 | }
|
36 | addRollbackListener(f) {
|
37 | if (!f || !(f instanceof Function)) {
|
38 | throw new TransactionError('Provided input to addRollbackListener is not a function');
|
39 | }
|
40 | this.rollbackListeners.push(f);
|
41 | }
|
42 | addEndListener(f) {
|
43 | if (!f || !(f instanceof Function)) {
|
44 | throw new TransactionError('Provided input to addEndListener is not a function');
|
45 | }
|
46 | this.endListeners.push(f);
|
47 | }
|
48 | |
49 |
|
50 |
|
51 | async end() {
|
52 | if (this.began) {
|
53 | if (this.finished) {
|
54 |
|
55 | throw new TransactionError('Transaction is already finished');
|
56 | }
|
57 | this.finished = true;
|
58 | if (this.error) {
|
59 |
|
60 | await this.callListeners(this.rollbackListeners);
|
61 | }
|
62 | else {
|
63 | await this.callListeners(this.commitListeners);
|
64 | }
|
65 | }
|
66 | await this.callListeners(this.endListeners);
|
67 | }
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 | callListeners(listeners) {
|
75 | if (listeners && listeners.length > 0) {
|
76 | return Promise.all(listeners.map((listener) => listener(this)).filter((resp) => !!resp));
|
77 | }
|
78 | return Promise.resolve();
|
79 |
|
80 |
|
81 |
|
82 |
|
83 |
|
84 |
|
85 | }
|
86 | }
|
87 | exports.Transaction = Transaction;
|
88 | Transaction.idInc = 1;
|
89 |
|
\ | No newline at end of file |