Debian Codegraph @

addons/point_of_sale/static/src/app/models/utils/indexed_db.js

raw
1 import { logPosMessage } from "@point_of_sale/app/utils/pretty_console_log";
2
3 const BATCH_SIZE = 500; // Can be adjusted based on performance testing
4 const TRANSACTION_TIMEOUT = 5000; // 5 seconds timeout for transactions
5 const CONSOLE_COLOR = "#3ba9ff";
6
7 export default class IndexedDB {
8 constructor(dbName, dbVersion, dbStores, whenReady) {
9 this.db = null;
10 this.dbName = dbName;
11 this.dbVersion = dbVersion;
12 this.dbStores = dbStores;
13 this.dbInstance = null;
14 this.activeTransactions = new Set();
15 this.databaseEventListener(whenReady);
16 }
17
18 databaseEventListener(whenReady) {
19 const indexedDB =
20 window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
21
22 if (!indexedDB) {
23 logPosMessage(
24 "IndexedDB",
25 "databaseEventListener",
26 "Your browser does not support IndexedDB. Data will not be saved.",
27 CONSOLE_COLOR
28 );
29 }
30
31 this.dbInstance = indexedDB;
32 let dbInstance;
33 if (this.dbVersion) {
34 dbInstance = indexedDB.open(this.dbName, this.dbVersion);
35 } else {
36 dbInstance = indexedDB.open(this.dbName);
37 }
38 dbInstance.onerror = (event) => {
39 logPosMessage(
40 "IndexedDB",
41 "databaseEventListener",
42 `Error opening IndexedDB: ${event.target.errorCode}`,
43 CONSOLE_COLOR
44 );
45 };
46 dbInstance.onsuccess = (event) => {
47 this.db = event.target.result;
48
49 const actualStoreNames = this.db.objectStoreNames;
50 let needsUpgrade = false;
51
52 for (const [, storeName] of this.dbStores) {
53 if (!actualStoreNames.contains(storeName)) {
54 logPosMessage(
55 "IndexedDB",
56 "onsuccess",
57 `Schema mismatch: Store '${storeName}' is missing. Triggering upgrade.`,
58 CONSOLE_COLOR
59 );
60 needsUpgrade = true;
61 break;
62 }
63 }
64
65 if (needsUpgrade) {
66 const newVersion = this.db.version + 1;
67 this.db.close();
68 this.dbVersion = newVersion;
69
70 logPosMessage(
71 "IndexedDB",
72 "onsuccess",
73 `Upgrading from v${newVersion - 1} to v${newVersion}...`,
74 CONSOLE_COLOR
75 );
76
77 this.databaseEventListener(whenReady);
78 return;
79 }
80
81 logPosMessage(
82 "IndexedDB",
83 "databaseEventListener",
84 `IndexedDB ${this.dbVersion} Ready`,
85 CONSOLE_COLOR
86 );
87 whenReady();
88 };
89 dbInstance.onupgradeneeded = (event) => {
90 for (const [id, storeName] of this.dbStores) {
91 if (!event.target.result.objectStoreNames.contains(storeName)) {
92 event.target.result.createObjectStore(storeName, { keyPath: id });
93 }
94 }
95 };
96 }
97
98 async promises(storeName, arrData, method) {
99 if (!arrData?.length) {
100 return;
101 }
102
103 // Batch processing for large arrays to avoid performance issues
104 // or transaction failures due to large data sets
105 const results = [];
106 for (let i = 0; i < arrData.length; i += BATCH_SIZE) {
107 let timeoutId;
108 let finished = false;
109
110 const batch = arrData.slice(i, i + BATCH_SIZE);
111 const transaction = this.getNewTransaction([storeName], "readwrite");
112
113 if (!transaction) {
114 results.push(Promise.reject("Transaction could not be created"));
115 continue;
116 }
117
118 const doneMethod = () => {
119 finished = true;
120 clearTimeout(timeoutId);
121 this.activeTransactions.delete(transaction);
122 };
123
124 // Mark transaction as finished in all cases
125 transaction.oncomplete = doneMethod;
126 transaction.onabort = doneMethod;
127 transaction.onerror = doneMethod;
128 transaction.onsuccess = doneMethod;
129
130 const batchPromise = new Promise((resolve, reject) => {
131 const store = transaction.objectStore(storeName);
132 let completed = 0;
133 let hasError = false;
134
135 timeoutId = setTimeout(() => {
136 if (!finished) {
137 reject(new Error("IndexedDB transaction timeout"));
138 try {
139 transaction.abort();
140 } catch (e) {
141 logPosMessage(
142 "IndexedDB",
143 method,
144 `Error aborting transaction: ${e.message}`,
145 CONSOLE_COLOR
146 );
147 }
148 }
149 }, TRANSACTION_TIMEOUT);
150
151 logPosMessage(
152 "IndexedDB",
153 method,
154 `Processing ${batch.length} items in store ${storeName}`,
155 CONSOLE_COLOR
156 );
157
158 for (const data of batch) {
159 try {
160 const deepCloned = JSON.parse(JSON.stringify(data));
161 const request = store[method](deepCloned);
162
163 request.onsuccess = () => {
164 completed++;
165 if (completed === batch.length && !hasError && !finished) {
166 clearTimeout(timeoutId);
167 resolve();
168 }
169 };
170
171 request.onerror = (event) => {
172 hasError = true;
173 clearTimeout(timeoutId);
174 logPosMessage(
175 "IndexedDB",
176 method,
177 `Error processing ${method} for ${storeName}: ${event.target?.error}`,
178 CONSOLE_COLOR
179 );
180 reject(event.target?.error || "Unknown error");
181 };
182 } catch {
183 logPosMessage(
184 "IndexedDB",
185 method,
186 `Error processing ${method} for ${storeName}: Invalid data format`,
187 CONSOLE_COLOR
188 );
189 }
190 }
191 });
192
193 const result = await batchPromise
194 .then(() => ({ status: "fulfilled" }))
195 .catch((err) => ({ status: "rejected", reason: err }));
196 results.push(result);
197 }
198
199 return results;
200 }
201
202 getNewTransaction(dbStore) {
203 try {
204 if (!this.db) {
205 return false;
206 }
207
208 const transaction = this.db.transaction(dbStore, "readwrite");
209 this.activeTransactions.add(transaction);
210 return transaction;
211 } catch (e) {
212 logPosMessage(
213 "IndexedDB",
214 "getNewTransaction",
215 `Error creating transaction: ${e.message}`,
216 CONSOLE_COLOR
217 );
218 return false;
219 }
220 }
221
222 reset() {
223 if (!this.dbInstance) {
224 return false;
225 }
226 this.dbInstance.deleteDatabase(this.dbName);
227 return true;
228 }
229
230 create(storeName, arrData) {
231 if (!arrData?.length) {
232 return;
233 }
234 return this.promises(storeName, arrData, "put");
235 }
236
237 readAll(store = [], retry = 0) {
238 const storeNames = store.length > 0 ? store : this.dbStores.map((store) => store[1]);
239 const transaction = this.getNewTransaction(storeNames, "readonly");
240
241 if (!transaction && retry < 5) {
242 return this.readAll(store, retry + 1);
243 } else if (!transaction) {
244 return new Promise((reject) => reject(false));
245 }
246
247 const removeTransaction = () => {
248 this.activeTransactions.delete(transaction);
249 };
250
251 transaction.oncomplete = removeTransaction;
252 transaction.onabort = removeTransaction;
253 transaction.onerror = removeTransaction;
254 transaction.onsuccess = removeTransaction;
255
256 const promises = storeNames.map(
257 (store) =>
258 new Promise((resolve, reject) => {
259 const objectStore = transaction.objectStore(store);
260 const request = objectStore.getAll();
261
262 const errorMethod = (event) => {
263 logPosMessage(
264 "IndexedDB",
265 "readAll",
266 `Error reading data from store ${store}: ${event.target.error}`,
267 CONSOLE_COLOR
268 );
269 reject(event.target.error || "Unknown error");
270 };
271
272 const successMethod = (event) => {
273 const result = event.target.result;
274 resolve({ [store]: result });
275 };
276
277 request.onerror = errorMethod;
278 request.onabort = errorMethod;
279 request.onsuccess = successMethod;
280 })
281 );
282
283 return Promise.allSettled(promises).then((results) =>
284 results.reduce((acc, result) => {
285 if (result.status === "fulfilled") {
286 return { ...acc, ...result.value };
287 } else {
288 return acc;
289 }
290 }, {})
291 );
292 }
293
294 delete(storeName, uuids) {
295 if (!uuids?.length) {
296 return;
297 }
298 return this.promises(storeName, uuids, "delete");
299 }
300 }