All files / src/todos todo.repository.ts

62.19% Statements 51/82
50% Branches 5/10
61.11% Functions 11/18
61.25% Lines 49/80

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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 3233x 3x 3x   3x     3x 15x     15x       3x                             10x                             1x             2x                       3x     3x         3x     3x         3x     3x         3x     3x         3x     3x 2x                       2x                 2x 1x         1x     2x 1x         1x                 1x     1x         1x         1x         1x           1x 1x 1x 1x                                                     1x         1x   1x             1x         1x   1x                                                 1x 1x       1x                                                                 1x         1x                                                                    
import { Injectable } from "@nestjs/common";
import { TodoEntity } from "./todo.entity";
import { RedisService } from "../redis/redis.service";
import type { RedisPipeline } from "../common/types/redis.types";
import { UserScopedRedisRepository } from "../common/repositories/user-scoped-redis.repository";
 
@Injectable()
export class TodoRepository extends UserScopedRedisRepository<TodoEntity> {
  protected entityName = "todo";
 
  constructor(redisService: RedisService) {
    super(redisService);
  }
 
  protected serialize(todo: TodoEntity): Record<string, string> {
    return {
      id: todo.id,
      title: todo.title,
      description: todo.description || "",
      completed: todo.completed.toString(),
      priority: todo.priority,
      categoryId: todo.categoryId,
      dueDate: todo.dueDate.toISOString(),
      createdAt: todo.createdAt.toISOString(),
      updatedAt: todo.updatedAt.toISOString(),
      userId: todo.userId,
    };
  }
 
  protected deserialize(data: Record<string, string>): TodoEntity {
    return new TodoEntity({
      id: data.id,
      title: data.title,
      description: data.description,
      completed: data.completed === "true",
      priority: data.priority as "high" | "medium" | "low",
      categoryId: data.categoryId || "default",
      dueDate: new Date(data.dueDate),
      createdAt: new Date(data.createdAt),
      updatedAt: new Date(data.updatedAt),
      userId: data.userId,
    });
  }
 
  protected createEntity(data: Partial<TodoEntity>): TodoEntity {
    return new TodoEntity(data);
  }
 
  protected updateEntity(
    existing: TodoEntity,
    updates: Partial<TodoEntity>,
  ): TodoEntity {
    return new TodoEntity({
      ...existing,
      ...updates,
      updatedAt: new Date(),
    });
  }
 
  protected updateUserIndexes(
    pipeline: RedisPipeline,
    newTodo: TodoEntity,
    oldTodo: TodoEntity | null,
  ): void {
    const userId = newTodo.userId;
 
    // 날짜별 인덱스
    const dateKey = this.generateUserIndexKey(
      userId,
      "date",
      newTodo.dueDate.toISOString().split("T")[0],
    );
    pipeline.sadd(dateKey, newTodo.id);
 
    // 카테고리별 인덱스
    const categoryKey = this.generateUserIndexKey(
      userId,
      "category",
      newTodo.categoryId,
    );
    pipeline.sadd(categoryKey, newTodo.id);
 
    // 완료 상태별 인덱스
    const completedKey = this.generateUserIndexKey(
      userId,
      "completed",
      newTodo.completed.toString(),
    );
    pipeline.sadd(completedKey, newTodo.id);
 
    // 우선순위별 인덱스
    const priorityKey = this.generateUserIndexKey(
      userId,
      "priority",
      newTodo.priority,
    );
    pipeline.sadd(priorityKey, newTodo.id);
 
    // 기존 인덱스에서 제거 (업데이트인 경우)
    if (oldTodo) {
      Iif (
        oldTodo.dueDate.toISOString().split("T")[0] !==
        newTodo.dueDate.toISOString().split("T")[0]
      ) {
        const oldDateKey = this.generateUserIndexKey(
          userId,
          "date",
          oldTodo.dueDate.toISOString().split("T")[0],
        );
        pipeline.srem(oldDateKey, newTodo.id);
      }
 
      Iif (oldTodo.categoryId !== newTodo.categoryId) {
        const oldCategoryKey = this.generateUserIndexKey(
          userId,
          "category",
          oldTodo.categoryId,
        );
        pipeline.srem(oldCategoryKey, newTodo.id);
      }
 
      if (oldTodo.completed !== newTodo.completed) {
        const oldCompletedKey = this.generateUserIndexKey(
          userId,
          "completed",
          oldTodo.completed.toString(),
        );
        pipeline.srem(oldCompletedKey, newTodo.id);
      }
 
      if (oldTodo.priority !== newTodo.priority) {
        const oldPriorityKey = this.generateUserIndexKey(
          userId,
          "priority",
          oldTodo.priority,
        );
        pipeline.srem(oldPriorityKey, newTodo.id);
      }
    }
  }
 
  protected removeUserEntityIndexes(
    pipeline: RedisPipeline,
    todo: TodoEntity,
  ): void {
    const userId = todo.userId;
 
    // 모든 인덱스에서 제거
    const dateKey = this.generateUserIndexKey(
      userId,
      "date",
      todo.dueDate.toISOString().split("T")[0],
    );
    const categoryKey = this.generateUserIndexKey(
      userId,
      "category",
      todo.categoryId,
    );
    const completedKey = this.generateUserIndexKey(
      userId,
      "completed",
      todo.completed.toString(),
    );
    const priorityKey = this.generateUserIndexKey(
      userId,
      "priority",
      todo.priority,
    );
 
    pipeline.srem(dateKey, todo.id);
    pipeline.srem(categoryKey, todo.id);
    pipeline.srem(completedKey, todo.id);
    pipeline.srem(priorityKey, todo.id);
  }
 
  protected async removeUserIndexes(
    pipeline: RedisPipeline,
    userId: string,
  ): Promise<void> {
    // 사용자의 모든 인덱스 제거 (패턴 매칭 사용)
    const pattern = this.redisService.generateKey(
      this.entityName,
      "user",
      userId,
      "index",
      "*",
    );
    const keys = await this.redisService.keys(pattern);
 
    keys.forEach((key) => {
      pipeline.del(key);
    });
  }
 
  // 특화된 검색 메서드들
  async findByUserIdAndCategory(
    userId: string,
    categoryId: string,
  ): Promise<TodoEntity[]> {
    const categoryKey = this.generateUserIndexKey(
      userId,
      "category",
      categoryId,
    );
    const todoIds = await this.redisService.smembers(categoryKey);
 
    return this.findByIds(todoIds);
  }
 
  async findByUserIdAndCompleted(
    userId: string,
    completed: boolean,
  ): Promise<TodoEntity[]> {
    const completedKey = this.generateUserIndexKey(
      userId,
      "completed",
      completed.toString(),
    );
    const todoIds = await this.redisService.smembers(completedKey);
 
    return this.findByIds(todoIds);
  }
 
  async findByUserIdAndPriority(
    userId: string,
    priority: string,
  ): Promise<TodoEntity[]> {
    const priorityKey = this.generateUserIndexKey(userId, "priority", priority);
    const todoIds = await this.redisService.smembers(priorityKey);
 
    return this.findByIds(todoIds);
  }
 
  async findByUserIdAndDate(userId: string, date: Date): Promise<TodoEntity[]> {
    const dateKey = this.generateUserIndexKey(
      userId,
      "date",
      date.toISOString().split("T")[0],
    );
    const todoIds = await this.redisService.smembers(dateKey);
 
    return this.findByIds(todoIds);
  }
 
  async toggle(id: string): Promise<TodoEntity | null> {
    const existing = await this.findById(id);
    Iif (!existing) {
      return null;
    }
 
    return this.update(id, { completed: !existing.completed });
  }
 
  async updateCategoryForUser(
    userId: string,
    oldCategoryId: string,
    newCategoryId: string,
  ): Promise<number> {
    const todos = await this.findByUserIdAndCategory(userId, oldCategoryId);
    let updatedCount = 0;
 
    // Pipeline을 사용하여 배치 업데이트
    const pipeline = this.redisService.pipeline();
 
    for (const todo of todos) {
      const updated = this.updateEntity(todo, { categoryId: newCategoryId });
      const key = this.generateKey(todo.id);
      const serializedData = this.serialize(updated);
      pipeline.hmset(key, serializedData);
 
      // 인덱스 업데이트
      this.updateUserIndexes(pipeline, updated, todo);
      updatedCount++;
    }
 
    await pipeline.exec();
    return updatedCount;
  }
 
  async countByUserIdAndCompleted(
    userId: string,
    completed: boolean,
  ): Promise<number> {
    const completedKey = this.generateUserIndexKey(
      userId,
      "completed",
      completed.toString(),
    );
    return await this.redisService.scard(completedKey);
  }
 
  // 통계를 위한 효율적인 카운트 메서드들
  async getStatsForUser(userId: string): Promise<{
    total: number;
    completed: number;
    incomplete: number;
    byPriority: { high: number; medium: number; low: number };
  }> {
    const [total, completed, high, medium, low] = await Promise.all([
      this.countByUserId(userId),
      this.countByUserIdAndCompleted(userId, true),
      this.countByUserIdAndPriority(userId, "high"),
      this.countByUserIdAndPriority(userId, "medium"),
      this.countByUserIdAndPriority(userId, "low"),
    ]);
 
    return {
      total,
      completed,
      incomplete: total - completed,
      byPriority: { high, medium, low },
    };
  }
 
  private async countByUserIdAndPriority(
    userId: string,
    priority: string,
  ): Promise<number> {
    const priorityKey = this.generateUserIndexKey(userId, "priority", priority);
    return await this.redisService.scard(priorityKey);
  }
}