addition of new dashboard
This commit is contained in:
33
backend/modules/dashboard/cache.js
Normal file
33
backend/modules/dashboard/cache.js
Normal file
@@ -0,0 +1,33 @@
|
||||
import { getPool } from "../../db/index.js";
|
||||
|
||||
// Lockless: concurrent cold misses may both compute, last writer wins.
|
||||
export async function getCached(userId, tag, ttlMs, compute) {
|
||||
let client = await getPool();
|
||||
try {
|
||||
const hit = (
|
||||
await client.query(
|
||||
`SELECT data FROM cache
|
||||
WHERE user_id = $1 AND tag = $2
|
||||
AND updated_ts > NOW() - ($3 * interval '1 millisecond')`,
|
||||
[userId, tag, ttlMs],
|
||||
)
|
||||
).rows[0];
|
||||
if (hit) return hit.data;
|
||||
} finally {
|
||||
await client.release();
|
||||
}
|
||||
|
||||
const data = await compute();
|
||||
|
||||
client = await getPool();
|
||||
try {
|
||||
await client.query(
|
||||
`INSERT INTO cache (user_id, tag, data) VALUES ($1, $2, $3::jsonb)
|
||||
ON CONFLICT (user_id, tag) DO UPDATE SET data = EXCLUDED.data, updated_ts = NOW()`,
|
||||
[userId, tag, data],
|
||||
);
|
||||
} finally {
|
||||
await client.release();
|
||||
}
|
||||
return data;
|
||||
}
|
||||
Reference in New Issue
Block a user