UNPKG

2.95 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3class TransactionError extends Error {
4}
5exports.TransactionError = TransactionError;
6class Transaction {
7 constructor() {
8 // constructor(readonly: boolean) {
9 this.id = Transaction.idInc++;
10 // this.readonly = readonly;
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 * @return {Promise} A promise that executes all the callbacks necessary
50 */
51 async end() {
52 if (this.began) {
53 if (this.finished) {
54 // console.log('Transaction is already finished');
55 throw new TransactionError('Transaction is already finished');
56 }
57 this.finished = true;
58 if (this.error) {
59 // console.log(`Emitting rollback for ${this.error} ${this.error.stack}`);
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 // canDo(readonly) {
69 // return !this.readonly || readonly;
70 // }
71 // isReadonly() {
72 // return this.readonly;
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 // for (let i = 0; i < listeners.length; i++) {
80 // const result = listeners[i](this);
81 // if (result && result.then) {
82 // throw new TransactionError(`${type} listener returned a promise. Callbacks are expected to be synchronous`);
83 // }
84 // }
85 }
86}
87exports.Transaction = Transaction;
88Transaction.idInc = 1;
89//# sourceMappingURL=TransactionManager.js.map
\No newline at end of file