Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 2x 1x 1x | import { cacheDb } from './db'
import type { ShoppingList, Item } from '../types'
/**
* Write-through cache backed by IndexedDB.
* Lists and items are saved here after every successful API response.
* On network failure, stores fall back to this cache so the app still loads.
*/
export const CacheService = {
// ── Lists ──────────────────────────────────────────────────────────────
async saveLists(lists: ShoppingList[]): Promise<void> {
const now = Date.now()
await cacheDb.lists.bulkPut(lists.map(l => ({ ...l, _savedAt: now })))
},
async saveList(list: ShoppingList): Promise<void> {
await cacheDb.lists.put({ ...list, _savedAt: Date.now() })
},
async getLists(): Promise<ShoppingList[]> {
const rows = await cacheDb.lists.orderBy('_savedAt').reverse().toArray()
return rows.map(({ _savedAt, ...list }) => list as ShoppingList)
},
async removeList(listId: string): Promise<void> {
await cacheDb.lists.delete(listId)
await cacheDb.items.where('listId').equals(listId).delete()
},
// ── Items ──────────────────────────────────────────────────────────────
async saveItems(listId: string, items: Item[]): Promise<void> {
const now = Date.now()
// Replace entire list snapshot
await cacheDb.items.where('listId').equals(listId).delete()
if (items.length > 0) {
await cacheDb.items.bulkPut(items.map(i => ({ ...i, _savedAt: now })))
}
},
async saveItem(item: Item): Promise<void> {
await cacheDb.items.put({ ...item, _savedAt: Date.now() })
},
async getItems(listId: string): Promise<Item[]> {
const rows = await cacheDb.items.where('listId').equals(listId).toArray()
// Restore position order
rows.sort((a, b) => a.position - b.position)
return rows.map(({ _savedAt, ...item }) => item as Item)
},
async removeItem(itemId: string): Promise<void> {
await cacheDb.items.delete(itemId)
},
/** Update a single field in a cached item without a full save */
async patchItem(itemId: string, changes: Partial<Item>): Promise<void> {
await cacheDb.items.update(itemId, changes)
},
}
|