-
Notifications
You must be signed in to change notification settings - Fork 32
/
transaction.js
96 lines (76 loc) · 2.78 KB
/
transaction.js
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { DataSyncController, createRecord, createRecords, updateRecord, updateRecords, deleteRecord, deleteRecords } from "./datasync.js";
import { query } from "./querybuilder.js";
export class Transaction {
constructor() {
this.transactionId = null;
this.onClose = this.onClose.bind(this);
this.dataSyncController = DataSyncController.getInstance();
}
async start() {
const { transactionId } = await this.dataSyncController.sendMessage({ tag: 'StartTransaction' });
this.transactionId = transactionId;
this.dataSyncController.addEventListener('close', this.onClose);
}
async commit() {
if (this.transactionId === null) {
throw new Error('You need to call `.start()` before you can commit the transaction');
}
await this.dataSyncController.sendMessage({ tag: 'CommitTransaction', id: this.transactionId });
this.onClose();
}
async rollback() {
if (this.transactionId === null) {
throw new Error('You need to call `.start()` before you can rollback the transaction');
}
await this.dataSyncController.sendMessage({ tag: 'RollbackTransaction', id: this.transactionId });
this.onClose();
}
onClose() {
this.transactionId = null;
this.dataSyncController.removeEventListener('close', this.onClose);
}
getIdOrFail() {
if (this.transactionId === null) {
throw new Error('You need to call `.start()` before you can use this transaction');
}
return this.transactionId;
}
buildOptions() {
return { transactionId: this.getIdOrFail() };
}
query(table) {
const tableQuery = query(table);
tableQuery.transactionId = this.getIdOrFail();
return tableQuery;
}
createRecord(table, record) {
return createRecord(table, record, this.buildOptions());
}
createRecords(table, records) {
return createRecords(table, records, this.buildOptions());
}
updateRecord(table, id, patch) {
return updateRecord(table, id, patch, this.buildOptions());
}
updateRecords(table, ids, patch) {
return updateRecords(table, ids, patch, this.buildOptions());
}
deleteRecord(table, id) {
return deleteRecord(table, id, this.buildOptions());
}
deleteRecords(table, ids) {
return deleteRecords(table, ids, this.buildOptions());
}
}
export async function withTransaction(callback) {
const transaction = new Transaction();
await transaction.start();
try {
const result = await callback(transaction);
await transaction.commit();
return result;
} catch (exception) {
await transaction.rollback();
throw exception;
}
}