Team Ai
Apppublic

sanket3280/code-execution

sourceHugging Faceupdated 11mo agoView on Hugging Face
0likes
friendsCacheService.js104 linesDownload Raw Back to services
1const redis = require('../config/redis');2 3/**4 * Friends Cache Service using Redis5 * Caches friend lists and requests to reduce database queries6 */7class FriendsCacheService {8  constructor() {9    this.CACHE_TTL = 300; // 5 minutes10    this.FRIENDS_KEY_PREFIX = 'friends:';11    this.REQUESTS_KEY_PREFIX = 'friend_requests:';12  }13 14  /**15   * Get cached friends list16   */17  async getFriends(userId) {18    try {19      const key = `${this.FRIENDS_KEY_PREFIX}${userId}`;20      const cached = await redis.get(key);21      return cached ? JSON.parse(cached) : null;22    } catch (error) {23      console.error('Redis get friends error:', error);24      return null;25    }26  }27 28  /**29   * Cache friends list30   */31  async setFriends(userId, friends) {32    try {33      const key = `${this.FRIENDS_KEY_PREFIX}${userId}`;34      await redis.setex(key, this.CACHE_TTL, JSON.stringify(friends));35    } catch (error) {36      console.error('Redis set friends error:', error);37    }38  }39 40  /**41   * Get cached friend requests42   */43  async getFriendRequests(userId) {44    try {45      const key = `${this.REQUESTS_KEY_PREFIX}${userId}`;46      const cached = await redis.get(key);47      return cached ? JSON.parse(cached) : null;48    } catch (error) {49      console.error('Redis get requests error:', error);50      return null;51    }52  }53 54  /**55   * Cache friend requests56   */57  async setFriendRequests(userId, requests) {58    try {59      const key = `${this.REQUESTS_KEY_PREFIX}${userId}`;60      await redis.setex(key, this.CACHE_TTL, JSON.stringify(requests));61    } catch (error) {62      console.error('Redis set requests error:', error);63    }64  }65 66  /**67   * Invalidate user's friends cache68   */69  async invalidateFriends(userId) {70    try {71      const key = `${this.FRIENDS_KEY_PREFIX}${userId}`;72      await redis.del(key);73    } catch (error) {74      console.error('Redis invalidate friends error:', error);75    }76  }77 78  /**79   * Invalidate user's friend requests cache80   */81  async invalidateFriendRequests(userId) {82    try {83      const key = `${this.REQUESTS_KEY_PREFIX}${userId}`;84      await redis.del(key);85    } catch (error) {86      console.error('Redis invalidate requests error:', error);87    }88  }89 90  /**91   * Invalidate both users' caches when friendship changes92   */93  async invalidateBothUsers(userId1, userId2) {94    await Promise.all([95      this.invalidateFriends(userId1),96      this.invalidateFriends(userId2),97      this.invalidateFriendRequests(userId1),98      this.invalidateFriendRequests(userId2)99    ]);100  }101}102 103module.exports = new FriendsCacheService();104