Files
corescope-rx/src/queue.js
T
2026-06-15 11:10:18 +02:00

59 lines
1.9 KiB
JavaScript

// Offline-first capture buffer (IndexedDB). The field often has no cellular, so
// receptions are buffered locally and published when connectivity returns.
const DB_NAME = 'coredrive-rx';
const STORE = 'pending';
function openDB() {
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, 1);
req.onupgradeneeded = () => {
req.result.createObjectStore(STORE, { keyPath: 'id', autoIncrement: true });
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
export class Queue {
async add(record) {
const db = await openDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, 'readwrite');
tx.objectStore(STORE).add(record);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
// takeAll returns all pending records (with their ids) for a publish attempt.
async takeAll() {
const db = await openDB();
return new Promise((resolve, reject) => {
const req = db.transaction(STORE, 'readonly').objectStore(STORE).getAll();
req.onsuccess = () => resolve(req.result || []);
req.onerror = () => reject(req.error);
});
}
// remove deletes records by id once they are confirmed published.
async remove(ids) {
const db = await openDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, 'readwrite');
const store = tx.objectStore(STORE);
ids.forEach((id) => store.delete(id));
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
async count() {
const db = await openDB();
return new Promise((resolve, reject) => {
const req = db.transaction(STORE, 'readonly').objectStore(STORE).count();
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
}