Repository navigation
[Refactor] TypeORM 저장소 조회 로직 정리 - #84
Conversation
Walkthrough이 PR은 엔티티에 denormalized 외래키 필드를 도입하고, TypeORM QueryBuilder 기반 조회를 Repository 메서드 기반으로 통일하며, 입력 검증을 추가합니다. Cafeterias, Departments, Users 엔티티에 FK 필드를 추가하고, 여러 저장소에서 QueryBuilder를 Repository.find/findOne으로 리팩토링합니다. Changes엔티티 스키마 및 저장소 쿼리 리팩토링
🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
services/api/app/src/api/public/departments/application/departments.service.ts (1)
16-27:⚠️ Potential issue | 🔴 Critical | ⚡ Quick win캐시 키와 실제 쿼리 매개변수 불일치 문제
@CacheKey데코레이터는 원본page값으로 캐시 키를 생성하지만 (line 18), 실제 쿼리에는safePage를 사용합니다.예를 들어:
page = -1로 요청 시 캐시 키는departments:college:X:page:-1이 되지만, 실제로는page=1의 결과가 저장됩니다- 이후
page = 1로 요청 시 다른 캐시 키(departments:college:X:page:1)를 사용하므로 캐시 미스가 발생합니다캐시 키 생성에도
Math.max(page, 1)를 적용해야 합니다.🔧 캐시 키 수정 제안
`@CacheKey`({ key: ([collegeId, page]) => { - return `departments:college:${collegeId}:page:${page}`; + const safePage = Math.max(page, 1); + return `departments:college:${collegeId}:page:${safePage}`; }, }) public async findAll(collegeId: number, page: number): Promise<DepartmentListResult> { const safePage = Math.max(page, 1);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@services/api/app/src/api/public/departments/application/departments.service.ts` around lines 16 - 27, The cache key uses the raw page param while the query uses safePage, causing mismatched cache entries; update the `@CacheKey` callback used on findAll to compute the same normalized page (Math.max(page, 1)) as safePage so the cache key and the call to departmentsRepository.findByCollegeId use identical page values, ensuring keys like departments:college:{collegeId}:page:{safePage} are generated consistently.
🧹 Nitpick comments (1)
services/api/app/src/api/public/users/application/users.service.ts (1)
30-46: ⚡ Quick winFK 유효성 검증을 추가하는 것을 권장합니다.
campusId와departmentId가 실제로 DB에 존재하는지 검증하지 않습니다. 존재하지 않는 ID를 전달하면 DB 외래키 제약 위반으로 런타임 에러가 발생할 수 있습니다. 저장 전에 campus와 department의 존재 여부를 확인하는 것을 고려하세요.🛡️ 제안: FK 유효성 검증 추가
public async upsert( userId: string, campusId: number, departmentId: number, ): Promise<UpsertDepartmentResult> { + // Validate that campusId and departmentId exist in DB + // Consider injecting CampusRepository and DepartmentRepository + // to check existence before saving + const user = new User(); user.updateProfile(userId, campusId, departmentId); const userResult = await this.usersRepository.save(user);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@services/api/app/src/api/public/users/application/users.service.ts` around lines 30 - 46, The upsert method currently saves a User without verifying campusId and departmentId exist, causing possible FK violations; update upsert to first query the Campus and Department stores (e.g., via injected campusRepository and departmentRepository or corresponding service methods) to ensure both campusId and departmentId exist, throw a clear validation/error (e.g., BadRequest or NotFound) if either is missing, and only then call this.usersRepository.save(user) so that upsert (method name) validates FK references before persisting.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@services/api/app/src/api/public/colleges/infrastructure/colleges.repository.ts`:
- Around line 14-26: The findAll method can compute a negative skip when page <=
0; clamp the page to a minimum of 1 inside findAll (e.g., compute const safePage
= Math.max(1, page)) before calculating skip, then pass skip: limit * (safePage
- 1) to this.collegesRepository.findAndCount and keep the rest of the logic
unchanged so queries never receive a negative offset.
---
Outside diff comments:
In
`@services/api/app/src/api/public/departments/application/departments.service.ts`:
- Around line 16-27: The cache key uses the raw page param while the query uses
safePage, causing mismatched cache entries; update the `@CacheKey` callback used
on findAll to compute the same normalized page (Math.max(page, 1)) as safePage
so the cache key and the call to departmentsRepository.findByCollegeId use
identical page values, ensuring keys like
departments:college:{collegeId}:page:{safePage} are generated consistently.
---
Nitpick comments:
In `@services/api/app/src/api/public/users/application/users.service.ts`:
- Around line 30-46: The upsert method currently saves a User without verifying
campusId and departmentId exist, causing possible FK violations; update upsert
to first query the Campus and Department stores (e.g., via injected
campusRepository and departmentRepository or corresponding service methods) to
ensure both campusId and departmentId exist, throw a clear validation/error
(e.g., BadRequest or NotFound) if either is missing, and only then call
this.usersRepository.save(user) so that upsert (method name) validates FK
references before persisting.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 98af1d0d-03e4-429a-ace1-bafb389ea2bf
📒 Files selected for processing (12)
services/api/app/src/api/public/cafeterias/domain/entities/cafeteria-diet.entity.tsservices/api/app/src/api/public/cafeterias/domain/entities/cafeteria.entity.tsservices/api/app/src/api/public/cafeterias/infrastructure/cafeterias.repository.tsservices/api/app/src/api/public/colleges/infrastructure/colleges.repository.tsservices/api/app/src/api/public/departments/application/departments.service.tsservices/api/app/src/api/public/departments/domain/entities/department.entity.tsservices/api/app/src/api/public/departments/infrastructure/departments.repository.tsservices/api/app/src/api/public/notices/infrastructure/notice-categories.repository.tsservices/api/app/src/api/public/users/application/users.service.spec.tsservices/api/app/src/api/public/users/application/users.service.tsservices/api/app/src/api/public/users/domain/entities/users.entity.tsservices/api/app/src/api/public/users/infrastructure/users.repository.ts
📌 개요
✨ 작업 내용
🔥 변경 이유
🧪 테스트
pnpm --dir services/api/app test users.service.spec.ts -- --runInBandpnpm --dir services/api/app lint:checkpnpm --dir services/api/app test -- --runInBand🔗 관련 이슈
Summary by CodeRabbit
릴리스 노트
Refactor
Bug Fixes
Tests