Open History to see the last commit
1import { openDB } from "idb"
2import type { DBSchema, IDBPDatabase } from "idb"
3import type { Transaction, TransactionWithoutToObject } from "./types"
4
5/**
6 * Interface defining the database schema for transaction storage
7 */
8interface SyncDB extends DBSchema {
9 transactions: {
10 key: string
11 value: TransactionWithoutToObject
12 }
13}
14
15/**
16 * Provides persistent storage for transactions using IndexedDB
17 */
18export class TransactionStore {
19 private dbName = `sync-transactions`
20 private version = 1
21 private db: IDBPDatabase<SyncDB> | null = null
22
23 /**
24 * Gets or initializes the IndexedDB database connection
25 *
26 * @returns Promise resolving to the database connection
27 */
28 private async getDB(): Promise<IDBPDatabase<SyncDB>> {
29 if (this.db) return this.db
30
31 this.db = await openDB<SyncDB>(this.dbName, this.version, {
32 upgrade(db) {
33 if (!db.objectStoreNames.contains(`transactions`)) {
34 db.createObjectStore(`transactions`, { keyPath: `id` })
35 }
36 },
37 })
38
39 return this.db
40 }
41
42 /**
43 * Retrieves all transactions from the store
44 *
45 * @returns Promise resolving to an array of all transactions
46 */
47 async getTransactions(): Promise<Array<TransactionWithoutToObject>> {
48 const db = await this.getDB()
49 return db.getAll(`transactions`)
50 }
51
52 /**
53 * Stores a transaction in the database
54 *
55 * @param tx - The transaction to store
56 * @returns Promise that resolves when the operation is complete
57 */
58 async putTransaction(tx: Transaction): Promise<void> {
59 const db = await this.getDB()
60
61 const { isSynced, isPersisted, toObject, ...restOfTx } = tx
62 await db.put(`transactions`, restOfTx)
63 }
64
65 /**
66 * Deletes a transaction from the store
67 *
68 * @param id - The ID of the transaction to delete
69 * @returns Promise that resolves when the operation is complete
70 */
71 async deleteTransaction(id: string): Promise<void> {
72 const db = await this.getDB()
73 await db.delete(`transactions`, id)
74 }
75
76 /**
77 * Clears all transactions from the store
78 * Helper method primarily used for testing
79 *
80 * @returns Promise that resolves when all transactions are deleted
81 */
82 async clearAll(): Promise<void> {
83 const db = await this.getDB()
84 const txIds = await db.getAllKeys(`transactions`)
85 await Promise.all(txIds.map((id) => this.deleteTransaction(id)))
86 }
87}