Spaces:
Running
Running
File size: 8,881 Bytes
57f5158 | 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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | /**
* Message Cache Utility
* Lưu messages và conversations vào localStorage để hiển thị ngay lập tức (stale-while-revalidate)
*/
const CACHE_PREFIX = "vc_msgs_";
const CONV_CACHE_KEY = `${CACHE_PREFIX}conversations`;
const SPACES_CACHE_KEY = `${CACHE_PREFIX}spaces`;
const MEMBERS_CACHE_KEY = `${CACHE_PREFIX}members`;
const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
const MAX_CACHE_ENTRIES = 50; // Giới hạn số conversation/room được cache
function getKey(type, id) {
return `${CACHE_PREFIX}${type}_${id}`;
}
/**
* Get cached messages for a conversation or room
* @param {'dm' | 'room'} type
* @param {string} id - conversationId or roomId
* @returns {{ messages: Array, fetchedAt: number, page: number } | null}
*/
export function getCachedMessages(type, id) {
if (!id) return null;
try {
const raw = localStorage.getItem(getKey(type, id));
if (!raw) return null;
const parsed = JSON.parse(raw);
// Validate structure
if (!Array.isArray(parsed.messages)) return null;
return {
messages: parsed.messages,
fetchedAt: parsed.fetchedAt || 0,
page: parsed.page || 1,
};
} catch {
return null;
}
}
/**
* Save messages to cache
* @param {'dm' | 'room'} type
* @param {string} id
* @param {Array} messages
* @param {number} page
*/
export function setCachedMessages(type, id, messages, page = 1) {
if (!id || !Array.isArray(messages)) return;
try {
// Enforce max entries: remove oldest if exceeded
enforceMaxEntries();
const payload = {
messages,
fetchedAt: Date.now(),
page,
};
localStorage.setItem(getKey(type, id), JSON.stringify(payload));
} catch (err) {
// localStorage might be full — clear old caches
if (err.name === "QuotaExceededError") {
clearOldestCaches(10);
try {
const payload = {
messages,
fetchedAt: Date.now(),
page,
};
localStorage.setItem(getKey(type, id), JSON.stringify(payload));
} catch {
// Still full, skip caching
}
}
}
}
/**
* Check if cache is still valid (within TTL)
* @param {'dm' | 'room'} type
* @param {string} id
* @param {number} ttlMs
* @returns {boolean}
*/
export function isCacheValid(type, id, ttlMs = DEFAULT_TTL_MS) {
const cached = getCachedMessages(type, id);
if (!cached) return false;
return Date.now() - cached.fetchedAt < ttlMs;
}
/**
* Check if cache exists (regardless of TTL)
* @param {'dm' | 'room'} type
* @param {string} id
* @returns {boolean}
*/
export function hasCache(type, id) {
return getCachedMessages(type, id) !== null;
}
/**
* Clear cache for a specific conversation/room
* @param {'dm' | 'room'} type
* @param {string} id
*/
export function clearCache(type, id) {
if (!id) return;
try {
localStorage.removeItem(getKey(type, id));
} catch {
// ignore
}
}
/**
* Clear all message caches (including conversations)
*/
export function clearAllMessageCaches() {
try {
const keysToRemove = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.startsWith(CACHE_PREFIX)) {
keysToRemove.push(key);
}
}
keysToRemove.forEach((key) => localStorage.removeItem(key));
} catch {
// ignore
}
}
// Helper: enforce max cache entries
function enforceMaxEntries() {
const entries = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.startsWith(CACHE_PREFIX)) {
try {
const raw = localStorage.getItem(key);
const parsed = JSON.parse(raw);
entries.push({ key, fetchedAt: parsed.fetchedAt || 0 });
} catch {
// ignore invalid entries
}
}
}
if (entries.length > MAX_CACHE_ENTRIES) {
// Sort by fetchedAt ascending (oldest first)
entries.sort((a, b) => a.fetchedAt - b.fetchedAt);
const toRemove = entries.slice(0, entries.length - MAX_CACHE_ENTRIES);
toRemove.forEach((e) => localStorage.removeItem(e.key));
}
}
// ==================== Conversations Cache ====================
/**
* Get cached conversations list
* @returns {{ conversations: Array, fetchedAt: number } | null}
*/
export function getCachedConversations() {
try {
const raw = localStorage.getItem(CONV_CACHE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed.conversations)) return null;
return {
conversations: parsed.conversations,
fetchedAt: parsed.fetchedAt || 0,
};
} catch {
return null;
}
}
/**
* Save conversations list to cache
* @param {Array} conversations
*/
export function setCachedConversations(conversations) {
if (!Array.isArray(conversations)) return;
try {
const payload = {
conversations,
fetchedAt: Date.now(),
};
localStorage.setItem(CONV_CACHE_KEY, JSON.stringify(payload));
} catch (err) {
if (err.name === "QuotaExceededError") {
clearAllMessageCaches();
try {
localStorage.setItem(CONV_CACHE_KEY, JSON.stringify({
conversations,
fetchedAt: Date.now(),
}));
} catch {
// skip
}
}
}
}
/**
* Check if conversations cache is valid
* @param {number} ttlMs
* @returns {boolean}
*/
export function isConversationsCacheValid(ttlMs = DEFAULT_TTL_MS) {
const cached = getCachedConversations();
if (!cached) return false;
return Date.now() - cached.fetchedAt < ttlMs;
}
/**
* Check if conversations cache exists
* @returns {boolean}
*/
export function hasConversationsCache() {
return getCachedConversations() !== null;
}
// ==================== Spaces & Rooms Cache ====================
/**
* Get cached spaces and roomsMap
* @returns {{ spaces: Array, roomsMap: Object, fetchedAt: number } | null}
*/
export function getCachedSpaces() {
try {
const raw = localStorage.getItem(SPACES_CACHE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed.spaces)) return null;
return {
spaces: parsed.spaces,
roomsMap: parsed.roomsMap || {},
fetchedAt: parsed.fetchedAt || 0,
};
} catch {
return null;
}
}
/**
* Save spaces and roomsMap to cache
* @param {Array} spaces
* @param {Object} roomsMap
*/
export function setCachedSpaces(spaces, roomsMap) {
if (!Array.isArray(spaces)) return;
try {
const payload = {
spaces,
roomsMap: roomsMap || {},
fetchedAt: Date.now(),
};
localStorage.setItem(SPACES_CACHE_KEY, JSON.stringify(payload));
} catch (err) {
if (err.name === "QuotaExceededError") {
clearAllMessageCaches();
try {
localStorage.setItem(SPACES_CACHE_KEY, JSON.stringify({
spaces,
roomsMap: roomsMap || {},
fetchedAt: Date.now(),
}));
} catch {
// skip
}
}
}
}
/**
* Check if spaces cache exists
* @returns {boolean}
*/
export function hasSpacesCache() {
return getCachedSpaces() !== null;
}
// ==================== Members Cache ====================
/**
* Get cached membersMap
* @returns {{ membersMap: Object, fetchedAt: number } | null}
*/
export function getCachedMembers() {
try {
const raw = localStorage.getItem(MEMBERS_CACHE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw);
return {
membersMap: parsed.membersMap || {},
fetchedAt: parsed.fetchedAt || 0,
};
} catch {
return null;
}
}
/**
* Save membersMap to cache
* @param {Object} membersMap
*/
export function setCachedMembers(membersMap) {
if (!membersMap || typeof membersMap !== "object") return;
try {
const payload = {
membersMap,
fetchedAt: Date.now(),
};
localStorage.setItem(MEMBERS_CACHE_KEY, JSON.stringify(payload));
} catch (err) {
if (err.name === "QuotaExceededError") {
clearAllMessageCaches();
try {
localStorage.setItem(MEMBERS_CACHE_KEY, JSON.stringify({
membersMap,
fetchedAt: Date.now(),
}));
} catch {
// skip
}
}
}
}
/**
* Check if members cache exists
* @returns {boolean}
*/
export function hasMembersCache() {
return getCachedMembers() !== null;
}
// Helper: clear N oldest caches
function clearOldestCaches(count) {
const entries = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.startsWith(CACHE_PREFIX)) {
try {
const raw = localStorage.getItem(key);
const parsed = JSON.parse(raw);
entries.push({ key, fetchedAt: parsed.fetchedAt || 0 });
} catch {
// ignore
}
}
}
entries.sort((a, b) => a.fetchedAt - b.fetchedAt);
entries.slice(0, count).forEach((e) => localStorage.removeItem(e.key));
}
|