Files
Isuru Bimsara 81d0e65686 first commit
2026-08-14 22:46:02 +05:30

129 lines
2.7 KiB
JavaScript

/**
* Copyright (c) 2026 Niolla
* All rights reserved.
*
* This source code is proprietary and confidential.
* Unauthorized copying, modification, distribution, or use
* of this file, via any medium, is strictly prohibited.
*/
// app/utils/cache.util.js
const redis = require("../config/redisClient");
const { log } = require("./consoleLog.utill");
const db = require("../models");
const User = db.User;
///////////////////////////////
// User Cache //
/////////////////////////////
const CACHE_TTL = 20 * 60; // 20 minutes (in seconds)
const getCacheKey = (email) => `user:${email}`;
async function getCachedUser(email) {
const key = getCacheKey(email);
try {
// 1. Check Redis first
if (process.env.CACHE === "true") {
const cached = await redis.get(key);
if (cached) {
log("⚡ Cache HIT - returning user from Redis");
return JSON.parse(cached);
}
}
log("Cache MISS - fetching user from DB");
// 2. Fetch from DB
const user = await User.findOne({ where: { email } });
if (!user) return null;
const plainUser = user.get({ plain: true });
// 3. Store in Redis
if (process.env.CACHE === "true") {
await redis.set(
key,
JSON.stringify(plainUser),
"EX",
CACHE_TTL
);
}
return plainUser;
} catch (err) {
log("Error fetching user:", err);
throw new Error("Failed to fetch user");
}
}
// Invalidate cache
async function clearUserCache(email) {
const key = getCacheKey(email);
try {
await redis.del(key);
log(`Cache cleared for user: ${email}`);
} catch (err) {
log("Error clearing cache:", err);
}
}
///////////////////////////////
// Permission Cache //
/////////////////////////////
const PERM_TTL = 10 * 60;
const getPermKey = (userId) => `perm:user:${userId}`;
async function getCachedPermissions(userId) {
if (process.env.CACHE !== "true") return null;
try {
const cached = await redis.get(getPermKey(userId));
return cached ? JSON.parse(cached) : null;
} catch (err) {
console.log("Cache read error:", err);
return null;
}
}
async function setCachedPermissions(userId, permissions) {
if (process.env.CACHE !== "true") return;
try {
await redis.set(
getPermKey(userId),
JSON.stringify(permissions),
"EX",
PERM_TTL
);
} catch (err) {
console.log("Cache write error:", err);
}
}
async function clearPermissionCache(userId) {
try {
await redis.del(getPermKey(userId));
} catch (err) {
console.log("Cache delete error:", err);
}
}
module.exports = {
getCachedUser,
clearUserCache,
getCachedPermissions,
setCachedPermissions,
clearPermissionCache
};