All files / src/user-settings user-settings.repository.ts

100% Statements 42/42
100% Branches 3/3
100% Functions 9/9
100% Lines 40/40

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 1405x 5x 5x     5x 10x     7x 7x   7x 3x     4x 4x                                   3x           1x             1x 1x         2x       2x         2x           4x             2x 2x           2x             2x 2x   2x 1x     1x           2x             1x 1x       2x 2x         2x 2x   2x         2x   2x 1x 1x     2x      
import { Injectable } from "@nestjs/common";
import { UserSettingsEntity } from "./user-settings.entity";
import { RedisService } from "../redis/redis.service";
 
@Injectable()
export class UserSettingsRepository {
  constructor(private readonly redisService: RedisService) {}
 
  async findByUserId(userId: string): Promise<UserSettingsEntity | null> {
    const settingsKey = this.redisService.generateKey("user-settings", userId);
    const settingsData = await this.redisService.get(settingsKey);
 
    if (!settingsData) {
      return null;
    }
 
    try {
      const parsedData = JSON.parse(settingsData) as {
        id: string;
        userId: string;
        createdAt: string;
        updatedAt: string;
        settings: {
          categories: Array<{
            id: string;
            name: string;
            color: string;
            createdAt: string;
            order?: number;
          }>;
          categoryFilter: { [categoryId: string]: boolean };
          theme: "light" | "dark" | "system";
          language: string;
        };
      };
      return new UserSettingsEntity({
        ...parsedData,
        createdAt: new Date(parsedData.createdAt),
        updatedAt: new Date(parsedData.updatedAt),
        settings: {
          ...parsedData.settings,
          categories: parsedData.settings.categories.map((cat) => ({
            ...cat,
            createdAt: new Date(cat.createdAt),
          })),
        },
      });
    } catch (error) {
      console.error("Error parsing user settings from Redis:", error);
      return null;
    }
  }
 
  async create(userSettings: UserSettingsEntity): Promise<UserSettingsEntity> {
    const settingsKey = this.redisService.generateKey(
      "user-settings",
      userSettings.userId,
    );
    const settingsListKey = this.redisService.generateKey(
      "user-settings",
      "list",
    );
 
    const settingsData = {
      ...userSettings,
      createdAt: userSettings.createdAt.toISOString(),
      updatedAt: userSettings.updatedAt.toISOString(),
      settings: {
        ...userSettings.settings,
        categories: userSettings.settings.categories.map((cat) => ({
          ...cat,
          createdAt: cat.createdAt.toISOString(),
        })),
      },
    };
 
    await this.redisService.set(settingsKey, JSON.stringify(settingsData));
    await this.redisService.zadd(
      settingsListKey,
      userSettings.createdAt.getTime(),
      userSettings.userId,
    );
 
    return userSettings;
  }
 
  async update(
    userId: string,
    userSettings: UserSettingsEntity,
  ): Promise<UserSettingsEntity | null> {
    const settingsKey = this.redisService.generateKey("user-settings", userId);
    const existingSettings = await this.findByUserId(userId);
 
    if (!existingSettings) {
      return null;
    }
 
    const settingsData = {
      ...userSettings,
      createdAt: userSettings.createdAt.toISOString(),
      updatedAt: userSettings.updatedAt.toISOString(),
      settings: {
        ...userSettings.settings,
        categories: userSettings.settings.categories.map((cat) => ({
          ...cat,
          createdAt: cat.createdAt.toISOString(),
        })),
      },
    };
 
    await this.redisService.set(settingsKey, JSON.stringify(settingsData));
    return userSettings;
  }
 
  async delete(userId: string): Promise<boolean> {
    const settingsKey = this.redisService.generateKey("user-settings", userId);
    const settingsListKey = this.redisService.generateKey(
      "user-settings",
      "list",
    );
 
    const result = await this.redisService.del(settingsKey);
    await this.redisService.zrem(settingsListKey, userId);
 
    return result > 0;
  }
 
  // Find or create user settings (helper method)
  async findOrCreate(userId: string): Promise<UserSettingsEntity> {
    let settings = await this.findByUserId(userId);
 
    if (!settings) {
      settings = UserSettingsEntity.createDefault(userId);
      await this.create(settings);
    }
 
    return settings;
  }
}