UNPKG

@tanstack/offline-transactions

Version:

Offline-first transaction capabilities for TanStack DB

85 lines (84 loc) • 2.49 kB
class KeyScheduler { constructor() { this.pendingTransactions = []; } schedule(transaction) { if (this.pendingTransactions.some((pending) => pending.id === transaction.id)) { return false; } this.pendingTransactions.push(transaction); this.pendingTransactions.sort( (a, b) => a.createdAt.getTime() - b.createdAt.getTime() ); return true; } getNext() { if (this.activeTransactionId !== void 0 || this.pendingTransactions.length === 0) { return void 0; } const firstTransaction = this.pendingTransactions[0]; return this.isReadyToRun(firstTransaction) ? firstTransaction : void 0; } isReadyToRun(transaction) { return Date.now() >= transaction.nextAttemptAt; } markStarted(transaction) { this.activeTransactionId = transaction.id; } markCompleted(transaction) { this.removeTransaction(transaction); this.activeTransactionId = void 0; } markFailed(_transaction) { this.activeTransactionId = void 0; } removeTransaction(transaction) { const index = this.pendingTransactions.findIndex( (tx) => tx.id === transaction.id ); if (index >= 0) { this.pendingTransactions.splice(index, 1); } } updateTransaction(transaction) { this.updateTransactions([transaction]); } getPendingCount() { return this.pendingTransactions.length; } getRunningCount() { return this.activeTransactionId === void 0 ? 0 : 1; } clear() { this.pendingTransactions = []; this.activeTransactionId = void 0; } /** @internal Reconcile one replay snapshot without canceling issued work. */ removePendingTransactions(transactionIds) { const ids = new Set(transactionIds); if (this.activeTransactionId !== void 0) ids.delete(this.activeTransactionId); this.pendingTransactions = this.pendingTransactions.filter( ({ id }) => !ids.has(id) ); return [...ids]; } getAllPendingTransactions() { return [...this.pendingTransactions]; } updateTransactions(updatedTransactions) { const updatedById = new Map( updatedTransactions.map((transaction) => [transaction.id, transaction]) ); this.pendingTransactions = this.pendingTransactions.map( (transaction) => updatedById.get(transaction.id) ?? transaction ); this.pendingTransactions.sort( (a, b) => a.createdAt.getTime() - b.createdAt.getTime() ); } } export { KeyScheduler }; //# sourceMappingURL=KeyScheduler.js.map