All files / src/common/repositories base-redis.repository.ts

100% Statements 73/73
100% Branches 14/14
100% Functions 15/15
100% Lines 71/71

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 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 19812x 12x                 12x         94x     74x       21x       1x                       28x 28x   28x 11x     17x       4x 4x   4x 2x     2x       15x 1x       14x 14x 24x 24x     14x 14x   14x 13x 19x         18x         14x       5x 5x 5x 5x     5x 5x 5x     5x   5x 5x       8x 8x 3x     5x 5x 5x     5x 5x     5x   5x 5x       8x 8x 3x     5x 5x     5x 5x 5x     5x   5x 5x       2x 2x       3x 3x   3x 3x 3x           3x   3x                                                          
import { Injectable } from "@nestjs/common";
import { RedisService } from "../../redis/redis.service";
import type { RedisPipeline } from "../types/redis.types";
import {
  BaseRepository,
  PaginatedResult,
  PaginationOptions,
} from "../interfaces/repository.interface";
 
@Injectable()
export abstract class BaseRedisRepository<T extends { id: string }>
  implements BaseRepository<T>
{
  protected abstract entityName: string;
 
  constructor(protected readonly redisService: RedisService) {}
 
  protected generateKey(id: string): string {
    return this.redisService.generateKey(this.entityName, id);
  }
 
  protected generateListKey(): string {
    return this.redisService.generateKey(this.entityName, "list");
  }
 
  protected generateIndexKey(field: string, value: string): string {
    return this.redisService.generateKey(
      this.entityName,
      "index",
      field,
      value,
    );
  }
 
  protected abstract serialize(entity: T): Record<string, string>;
  protected abstract deserialize(data: Record<string, string>): T;
 
  async findById(id: string): Promise<T | null> {
    const key = this.generateKey(id);
    const data = await this.redisService.hgetall(key);
 
    if (!data || Object.keys(data).length === 0) {
      return null;
    }
 
    return this.deserialize(data);
  }
 
  async findAll(): Promise<T[]> {
    const listKey = this.generateListKey();
    const ids = await this.redisService.zrange(listKey, 0, -1);
 
    if (ids.length === 0) {
      return [];
    }
 
    return this.findByIds(ids);
  }
 
  async findByIds(ids: string[]): Promise<T[]> {
    if (ids.length === 0) {
      return [];
    }
 
    // Redis Pipeline을 사용하여 배치 처리
    const pipeline = this.redisService.pipeline();
    ids.forEach((id) => {
      const key = this.generateKey(id);
      pipeline.hgetall(key);
    });
 
    const results = await pipeline.exec();
    const entities: T[] = [];
 
    if (results) {
      for (const [error, data] of results) {
        if (
          !error &&
          data &&
          Object.keys(data as Record<string, string>).length > 0
        ) {
          entities.push(this.deserialize(data as Record<string, string>));
        }
      }
    }
 
    return entities;
  }
 
  async create(entity: Partial<T>): Promise<T> {
    const newEntity = this.createEntity(entity);
    const key = this.generateKey(newEntity.id);
    const listKey = this.generateListKey();
    const serializedData = this.serialize(newEntity);
 
    // Pipeline을 사용하여 원자적 처리
    const pipeline = this.redisService.pipeline();
    pipeline.hmset(key, serializedData);
    pipeline.zadd(listKey, Date.now(), newEntity.id);
 
    // 인덱스 업데이트
    await this.updateIndexes(pipeline, newEntity, null);
 
    await pipeline.exec();
    return newEntity;
  }
 
  async update(id: string, updates: Partial<T>): Promise<T | null> {
    const existing = await this.findById(id);
    if (!existing) {
      return null;
    }
 
    const updated = this.updateEntity(existing, updates);
    const key = this.generateKey(id);
    const serializedData = this.serialize(updated);
 
    // Pipeline을 사용하여 원자적 처리
    const pipeline = this.redisService.pipeline();
    pipeline.hmset(key, serializedData);
 
    // 인덱스 업데이트
    await this.updateIndexes(pipeline, updated, existing);
 
    await pipeline.exec();
    return updated;
  }
 
  async delete(id: string): Promise<boolean> {
    const existing = await this.findById(id);
    if (!existing) {
      return false;
    }
 
    const key = this.generateKey(id);
    const listKey = this.generateListKey();
 
    // Pipeline을 사용하여 원자적 처리
    const pipeline = this.redisService.pipeline();
    pipeline.del(key);
    pipeline.zrem(listKey, id);
 
    // 인덱스 정리
    await this.removeFromIndexes(pipeline, existing);
 
    const results = await pipeline.exec();
    return results ? (results[0][1] as number) > 0 : false;
  }
 
  async exists(id: string): Promise<boolean> {
    const key = this.generateKey(id);
    return await this.redisService.exists(key);
  }
 
  async findPaginated(options: PaginationOptions): Promise<PaginatedResult<T>> {
    const { page, limit } = options;
    const offset = (page - 1) * limit;
 
    const listKey = this.generateListKey();
    const total = await this.redisService.zcard(listKey);
    const ids = await this.redisService.zrevrange(
      listKey,
      offset,
      offset + limit - 1,
    );
 
    const items = await this.findByIds(ids);
 
    return {
      items,
      total,
      page,
      limit,
      hasNext: offset + limit < total,
      hasPrev: page > 1,
    };
  }
 
  protected abstract createEntity(data: Partial<T>): T;
  protected abstract updateEntity(existing: T, updates: Partial<T>): T;
 
  // 하위 클래스에서 인덱스 관리를 위해 오버라이드할 수 있는 메서드들
  protected updateIndexes(
    _pipeline: RedisPipeline,
    _newEntity: T,
    _oldEntity: T | null,
  ): Promise<void> | void {
    // 기본 구현은 비어있음 - 하위 클래스에서 필요에 따라 구현
  }
 
  protected removeFromIndexes(
    _pipeline: RedisPipeline,
    _entity: T,
  ): Promise<void> | void {
    // 기본 구현은 비어있음 - 하위 클래스에서 필요에 따라 구현
  }
}