All files / src/common/repositories user-scoped-redis.repository.ts

100% Statements 52/52
100% Branches 10/10
93.75% Functions 15/16
100% Lines 49/49

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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 1754x 4x   4x       4x             34x       23x               22x                     4x 4x   4x 2x     2x       3x   3x 2x     1x       4x 4x   4x 1x       3x     3x 4x 4x       3x     3x 3x 4x       3x   3x 3x       3x 3x                 6x     6x   6x 6x     6x               2x     2x 2x     2x                                                               3x 3x 3x   3x           3x 1x     2x      
import { Injectable } from "@nestjs/common";
import { RedisService } from "../../redis/redis.service";
import type { RedisPipeline } from "../types/redis.types";
import { BaseRedisRepository } from "./base-redis.repository";
import { UserScopedRepository } from "../interfaces/repository.interface";
 
@Injectable()
export abstract class UserScopedRedisRepository<
    T extends { id: string; userId: string },
  >
  extends BaseRedisRepository<T>
  implements UserScopedRepository<T>
{
  constructor(redisService: RedisService) {
    super(redisService);
  }
 
  protected generateUserListKey(userId: string): string {
    return this.redisService.generateKey(this.entityName, "user", userId);
  }
 
  protected generateUserIndexKey(
    userId: string,
    field: string,
    value: string,
  ): string {
    return this.redisService.generateKey(
      this.entityName,
      "user",
      userId,
      "index",
      field,
      value,
    );
  }
 
  async findByUserId(userId: string): Promise<T[]> {
    const userListKey = this.generateUserListKey(userId);
    const ids = await this.redisService.zrevrange(userListKey, 0, -1);
 
    if (ids.length === 0) {
      return [];
    }
 
    return this.findByIds(ids);
  }
 
  async findByUserIdAndId(userId: string, id: string): Promise<T | null> {
    const entity = await this.findById(id);
 
    if (!entity || entity.userId !== userId) {
      return null;
    }
 
    return entity;
  }
 
  async deleteByUserId(userId: string): Promise<boolean> {
    const userListKey = this.generateUserListKey(userId);
    const ids = await this.redisService.zrange(userListKey, 0, -1);
 
    if (ids.length === 0) {
      return true;
    }
 
    // Pipeline을 사용하여 배치 삭제
    const pipeline = this.redisService.pipeline();
 
    // 각 엔티티 삭제
    ids.forEach((id) => {
      const key = this.generateKey(id);
      pipeline.del(key);
    });
 
    // 사용자별 리스트 삭제
    pipeline.del(userListKey);
 
    // 전역 리스트에서 항목들 제거
    const globalListKey = this.generateListKey();
    ids.forEach((id) => {
      pipeline.zrem(globalListKey, id);
    });
 
    // 사용자별 인덱스 정리
    await this.removeUserIndexes(pipeline, userId);
 
    const results = await pipeline.exec();
    return results ? results.some(([error]) => !error) : false;
  }
 
  async countByUserId(userId: string): Promise<number> {
    const userListKey = this.generateUserListKey(userId);
    return await this.redisService.zcard(userListKey);
  }
 
  protected async updateIndexes(
    pipeline: RedisPipeline,
    newEntity: T,
    oldEntity: T | null,
  ): Promise<void> {
    // 전역 인덱스 업데이트
    await super.updateIndexes(pipeline, newEntity, oldEntity);
 
    // 사용자별 리스트 관리
    const userListKey = this.generateUserListKey(newEntity.userId);
    const timestamp =
      (newEntity as { createdAt?: Date }).createdAt?.getTime() || Date.now();
    pipeline.zadd(userListKey, timestamp, newEntity.id);
 
    // 사용자별 인덱스 업데이트
    await this.updateUserIndexes(pipeline, newEntity, oldEntity);
  }
 
  protected async removeFromIndexes(
    pipeline: RedisPipeline,
    entity: T,
  ): Promise<void> {
    // 전역 인덱스 정리
    await super.removeFromIndexes(pipeline, entity);
 
    // 사용자별 리스트에서 제거
    const userListKey = this.generateUserListKey(entity.userId);
    pipeline.zrem(userListKey, entity.id);
 
    // 사용자별 인덱스 정리
    await this.removeUserEntityIndexes(pipeline, entity);
  }
 
  // 하위 클래스에서 구현할 사용자별 인덱스 관리 메서드들
  protected updateUserIndexes(
    _pipeline: RedisPipeline,
    _newEntity: T,
    _oldEntity: T | null,
  ): Promise<void> | void {
    // 기본 구현은 비어있음 - 하위 클래스에서 필요에 따라 구현
  }
 
  protected removeUserEntityIndexes(
    _pipeline: RedisPipeline,
    _entity: T,
  ): Promise<void> | void {
    // 기본 구현은 비어있음 - 하위 클래스에서 필요에 따라 구현
  }
 
  protected removeUserIndexes(
    _pipeline: RedisPipeline,
    _userId: string,
  ): Promise<void> | void {
    // 기본 구현은 비어있음 - 하위 클래스에서 필요에 따라 구현
  }
 
  // 날짜 범위 검색을 위한 헬퍼 메서드
  async findByUserIdAndDateRange(
    userId: string,
    startDate: Date,
    endDate: Date,
  ): Promise<T[]> {
    const userListKey = this.generateUserListKey(userId);
    const startTimestamp = startDate.getTime();
    const endTimestamp = endDate.getTime();
 
    const ids = await this.redisService.zrangebyscore(
      userListKey,
      startTimestamp,
      endTimestamp,
    );
 
    if (ids.length === 0) {
      return [];
    }
 
    return this.findByIds(ids);
  }
}