diff options
Diffstat (limited to 'lib/db.ts')
| -rw-r--r-- | lib/db.ts | 43 |
1 files changed, 40 insertions, 3 deletions
@@ -100,7 +100,7 @@ async function dbReconnect() { async function archiveReconnect() { try { - await archive.connect(); + if (!archive.isOpen) await archive.connect(); } catch (err) { console.error("Failed to connect to Redis, retrying...", err); setTimeout(archiveReconnect, 5000); // Retry after 5 seconds @@ -130,9 +130,9 @@ export const g = async (k) => { } }; -export const s = (k, v) => { +export const s = (k, v, ttl?: number) => { if (k === "user:null" || k === "user:undefined") fail("null user"); - db.set(k, JSON.stringify(v)); + db.set(k, JSON.stringify(v), ttl ? { EX: ttl } : undefined); }; export const ga = async (k) => { @@ -152,6 +152,43 @@ export const sa = (k, v) => { archive.set(k, JSON.stringify(v)); }; +// Get with fallback to archive +export const gf = async (k) => { + let v = await db.get(k); + if (v === null) v = await archive.get(k); + try { + return JSON.parse(v); + } catch (e) { + return v; + } +}; + +// lRange with fallback to archive for missing items +export const lRangeWithArchive = async (k, start, end) => { + const items = await db.lRange(k, start, end); + return items || []; +}; + +// Get payment/invoice with archive fallback - for individual lookups +export const getWithArchive = async (prefix, id) => { + let v = await db.get(`${prefix}:${id}`); + if (v === null) v = await archive.get(`${prefix}:${id}`); + if (v === null) return null; + try { + const parsed = JSON.parse(v); + // If it's a reference to another key, follow it + if (typeof parsed === "string") { + let ref = await db.get(`${prefix}:${parsed}`); + if (ref === null) ref = await archive.get(`${prefix}:${parsed}`); + if (ref === null) return null; + return JSON.parse(ref); + } + return parsed; + } catch (e) { + return v; + } +}; + const retries = {}; export const t = async (k, f) => { try { |
