Source

utils/cache.utils.js

import { logger } from "@config/logger.js";
import { redisUtils } from "@config/redis.js";
/**
 * Lightweight caching helpers backed by Redis.
 * @category Helpers
 */
export class CacheService {
    // 1 day (in seconds)
    static ONE_DAY_TTL_SECONDS = 24 * 60 * 60;
    /**
     * Generate key for Redis cache.
     * @param {string} userId The user ID.
     * @returns {string} Redis key namespace.
     */
    static generateKey(userId) {
        return `user:${userId}`;
    }
    /**
     * Transform User document to ICurrentUserResponse format.
     * @param {IUserDocument} user The user to transform.
     * @returns {ICurrentUserResponse} Serialized user response.
     */
    static toUserResponse(user) {
        return {
            id: user._id.toString(),
            email: user.email,
            name: user.name,
            avatar: user.avatar || undefined,
            role: user.role,
            createdAt: user.createdAt,
            updatedAt: user.updatedAt,
        };
    }
    /**
     * Add user to Redis cache.
     * @param {ICurrentUserResponse} user The user to add to the cache.
     * @returns {Promise<void>} Resolves when the cache entry is stored.
     */
    static async addUser(user) {
        try {
            const key = this.generateKey(user.id);
            await redisUtils.set(key, JSON.stringify(user), this.ONE_DAY_TTL_SECONDS);
        }
        catch (error) {
            logger.warn({ error: error instanceof Error ? error.message : String(error) }, "Failed to set user in Redis cache");
        }
    }
    /**
     * Update user in Redis cache.
     * @param {ICurrentUserResponse} user The user to update in the cache.
     * @returns {Promise<void>} Resolves when potential cache updates finish.
     */
    static async updateUser(user) {
        try {
            const key = this.generateKey(user.id);
            // Check if user exists in cache
            const exists = await redisUtils.exists(key);
            if (exists) {
                await this.addUser(user);
            }
        }
        catch (error) {
            logger.warn({ error: error instanceof Error ? error.message : String(error) }, "Failed to update user in Redis cache");
        }
    }
    /**
     * Delete user from Redis cache
     * @param {string} userId The user ID to delete from the cache
     * @returns {Promise<void>} Resolves when the user is deleted from the cache.
     */
    static async deleteUser(userId) {
        try {
            const key = this.generateKey(userId);
            await redisUtils.del(key);
            logger.info({ userId }, "User deleted from Redis cache");
        }
        catch (error) {
            logger.warn({ error: error instanceof Error ? error.message : String(error), userId }, "Failed to delete user from Redis cache");
        }
    }
}