WIP PWA for Grain
next.grain.social
1// src/services/record-cache.js
2
3const cache = new Map();
4const listeners = new Map();
5
6function notify(key, data) {
7 const keyListeners = listeners.get(key);
8 if (keyListeners) {
9 for (const callback of keyListeners) {
10 callback(data);
11 }
12 }
13}
14
15export const recordCache = {
16 /**
17 * Get a cached record by key
18 * @param {string} key - Cache key (typically AT Protocol URI, or "profile:{handle}" for profiles)
19 * @returns {object|undefined} Cached record or undefined
20 */
21 get(key) {
22 return cache.get(key);
23 },
24
25 /**
26 * Set/merge record data. Dispatches update event.
27 * @param {string} key - Cache key (typically AT Protocol URI, or "profile:{handle}" for profiles)
28 * @param {object} data - Partial or full record data
29 */
30 set(key, data) {
31 const existing = cache.get(key) || {};
32 const merged = { ...existing, ...data };
33 cache.set(key, merged);
34 notify(key, merged);
35 },
36
37 /**
38 * Check if a key is cached
39 * @param {string} key - Cache key (typically AT Protocol URI, or "profile:{handle}" for profiles)
40 * @returns {boolean}
41 */
42 has(key) {
43 return cache.has(key);
44 },
45
46 /**
47 * Subscribe to changes for a specific key
48 * @param {string} key - Cache key (typically AT Protocol URI, or "profile:{handle}" for profiles)
49 * @param {function} callback - Called with updated data
50 */
51 subscribe(key, callback) {
52 if (!listeners.has(key)) {
53 listeners.set(key, new Set());
54 }
55 listeners.get(key).add(callback);
56 },
57
58 /**
59 * Unsubscribe from changes
60 * @param {string} key - Cache key (typically AT Protocol URI, or "profile:{handle}" for profiles)
61 * @param {function} callback - The callback to remove
62 */
63 unsubscribe(key, callback) {
64 const keyListeners = listeners.get(key);
65 if (keyListeners) {
66 keyListeners.delete(callback);
67 if (keyListeners.size === 0) {
68 listeners.delete(key);
69 }
70 }
71 },
72
73 /**
74 * Clear all cached data and subscriptions (useful for logout)
75 */
76 clear() {
77 cache.clear();
78 listeners.clear();
79 }
80};