Skip to content

fix: resolve issue #1396 - IIT Professor List and Stats Cache Invalidation on Modifications#1397

Closed
sonusharma6-dsa wants to merge 2 commits into
Sachinchaurasiya360:mainfrom
sonusharma6-dsa:fix-issue-1396
Closed

fix: resolve issue #1396 - IIT Professor List and Stats Cache Invalidation on Modifications#1397
sonusharma6-dsa wants to merge 2 commits into
Sachinchaurasiya360:mainfrom
sonusharma6-dsa:fix-issue-1396

Conversation

@sonusharma6-dsa
Copy link
Copy Markdown
Contributor

@sonusharma6-dsa sonusharma6-dsa commented Jun 4, 2026

Closes #1396

Summary by CodeRabbit

  • New Features

    • Cache middleware now supports optional custom time-to-live (TTL) and key prefix parameters, allowing for more granular control over caching behavior.
    • Professor data management operations now automatically invalidate associated cached entries when records are created, updated, or deleted, ensuring data consistency.
  • Tests

    • Updated test mocking implementation for ATS service validations.
  • Chores

    • Removed redundant import declarations.

@github-actions github-actions Bot added gssoc level:intermediate Requires moderate project understanding quality:clean Clean and well-structured contribution scope:backend Changes to server-side / API code labels Jun 4, 2026
@github-actions
Copy link
Copy Markdown

github-actions Bot commented Jun 4, 2026

Hi @sonusharma6-dsa, thanks for contributing to InternHack! 🎉

I have automatically:

  • 👤 Assigned this PR to you.
  • 🏷️ Applied the gssoc:approved label.

Our workflows will now analyze your changes to classify:

  • 📈 PR Difficulty: level:*
  • 🧩 PR Type: type:*
  • 🌟 PR Quality: quality:*

Tip

Ensure your PR description references the issue it resolves (e.g. Closes #123). This allows the bot to inherit any additional labels from that issue!

Happy coding! 🚀

@github-actions github-actions Bot added gssoc:approved Approved for GSSoC scoring type:bug Bug fixes type:performance Performance optimization changes type:testing Adds or improves tests labels Jun 4, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 4, 2026

Review Change Stack

Warning

Review limit reached

@sonusharma6-dsa, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 17 minutes and 2 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ceb3025d-1153-44be-958c-1ebfc6c31a0b

📥 Commits

Reviewing files that changed from the base of the PR and between 59b1929 and f3a882c.

📒 Files selected for processing (2)
  • server/src/module/ats/__tests__/ats.service.test.ts
  • server/src/module/professor/professor.service.ts
📝 Walkthrough

Walkthrough

This PR extends the cache system with flexible parameter support and implements cache invalidation for professor CRUD operations. Cache middleware gains optional custom TTL and key prefix parameters, while ProfessorService adds create/update/delete methods that clear the professor cache after modifications. Minor cleanup includes deduplicating an import and updating test type annotations.

Changes

Cache System Improvements

Layer / File(s) Summary
Cache middleware customization
server/src/middleware/cache.middleware.ts
cacheMiddleware signature extended to accept optional customTtl and customKeyPrefix parameters; TTL and cache key prefix computation now use custom values when provided, otherwise fall back to endpoint-specific configuration; response caching applies the computed TTL instead of always using the default.
Professor service CRUD with cache invalidation
server/src/module/professor/professor.service.ts
ProfessorService imports cacheDelPattern and adds three public async methods—create, update, delete—that perform Prisma CRUD operations on iitProfessor records and automatically clear cached entries matching the professors: pattern before returning the modified record.

Code Quality Fixes

Layer / File(s) Summary
Admin import deduplication and ATS test typing
server/src/module/admin/admin.controller.ts, server/src/module/ats/__tests__/ats.service.test.ts
Duplicate withAdvisoryLock import removed from admin.controller.ts; three ATS test cases updated with explicit args: any type annotations for prisma.atsScore.create mock implementations.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related issues

Suggested labels

type:bug

Poem

🐰 With custom TTLs now in hand,
And professors' cache swept clean and grand,
The cache system blinks and cheers,
No more stale data for professorial years!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The PR description is minimal but follows the repository template structure; however, most required sections are empty or incomplete. Fill in the Description, Type of Change, and Testing sections to provide complete context about what was changed and how it was tested.
Out of Scope Changes check ❓ Inconclusive Most changes directly address cache invalidation; however, adjustments to ats.service.test.ts and removal of a duplicate import in admin.controller.ts appear tangential to the primary objective. Clarify why test typing adjustments and the admin import removal are included; consider isolating unrelated changes into separate PRs if they address different concerns.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: implementing cache invalidation for IIT professor data on modifications to address issue #1396.
Linked Issues check ✅ Passed The PR successfully implements cache invalidation for professor data modifications: added create/update/delete methods to ProfessorService that call cacheDelPattern to clear cached professor entries.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions Bot added quality:exceptional Exceptional implementation quality and removed quality:clean Clean and well-structured contribution labels Jun 4, 2026
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
server/src/module/ats/__tests__/ats.service.test.ts (1)

337-339: ⚡ Quick win

Prefer more targeted type annotations over blanket any casts.

The current pattern (async (args: any) => ...) as any fixes compilation errors but removes all type checking for these mock implementations. Consider typing just the args parameter structure instead of casting the entire function:

-      vi.mocked(prisma.atsScore.create).mockImplementation(
-        (async (args: any) =>
-          ({ ...MOCK_ATS_ROW, overallScore: (args.data as any).overallScore })) as any,
-      );
+      vi.mocked(prisma.atsScore.create).mockImplementation(
+        async (args: { data: any }) =>
+          ({ ...MOCK_ATS_ROW, overallScore: args.data.overallScore }) as any,
+      );

This preserves the fix for compilation errors while maintaining better type safety. Apply the same pattern to the other two instances at lines 358-360 and 385-387.

Also applies to: 358-360, 385-387

🤖 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 `@server/src/module/ats/__tests__/ats.service.test.ts` around lines 337 - 339,
Replace the blanket any casts on the mock async callbacks with a focused param
type: instead of `(async (args: any) => ({ ...MOCK_ATS_ROW, overallScore:
(args.data as any).overallScore })) as any`, declare the function parameter with
a narrow shape (e.g. `async (args: { data: { overallScore: number } }) => ...`)
and remove the `as any` cast and the inner `(args.data as any)` cast; apply the
same change to the two other mock callbacks mentioned so that each mock returns
`{ ...MOCK_ATS_ROW, overallScore: args.data.overallScore }` while preserving
type safety.
🤖 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 `@server/src/module/professor/professor.service.ts`:
- Around line 110-125: The create/update/delete methods call
prisma.iitProfessor.* and then await cacheDelPattern("professors:"), which risks
throwing after the DB commit; change the cache invalidation to be non-fatal:
call cacheDelPattern asynchronously and handle its errors without bubbling them
(e.g., fire-and-forget or wrap in try/catch and only log failures) so that
failures to delete cache never roll back or surface after the DB write. Update
the create, update, and delete functions (references: create, update, delete
methods and cacheDelPattern) to ensure the DB operation result is returned even
if cache invalidation fails.

---

Nitpick comments:
In `@server/src/module/ats/__tests__/ats.service.test.ts`:
- Around line 337-339: Replace the blanket any casts on the mock async callbacks
with a focused param type: instead of `(async (args: any) => ({ ...MOCK_ATS_ROW,
overallScore: (args.data as any).overallScore })) as any`, declare the function
parameter with a narrow shape (e.g. `async (args: { data: { overallScore: number
} }) => ...`) and remove the `as any` cast and the inner `(args.data as any)`
cast; apply the same change to the two other mock callbacks mentioned so that
each mock returns `{ ...MOCK_ATS_ROW, overallScore: args.data.overallScore }`
while preserving type safety.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5ec4e7ac-b3b8-4d39-aa9f-e33186a7b63c

📥 Commits

Reviewing files that changed from the base of the PR and between e15a36c and 59b1929.

📒 Files selected for processing (4)
  • server/src/middleware/cache.middleware.ts
  • server/src/module/admin/admin.controller.ts
  • server/src/module/ats/__tests__/ats.service.test.ts
  • server/src/module/professor/professor.service.ts
💤 Files with no reviewable changes (1)
  • server/src/module/admin/admin.controller.ts

Comment on lines +110 to +125
async create(data: any) {
const record = await prisma.iitProfessor.create({ data });
await cacheDelPattern("professors:");
return record;
}

async update(id: number, data: any) {
const record = await prisma.iitProfessor.update({ where: { id }, data });
await cacheDelPattern("professors:");
return record;
}

async delete(id: number) {
const record = await prisma.iitProfessor.delete({ where: { id } });
await cacheDelPattern("professors:");
return record;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Do not surface mutation failure after the DB write has already committed.

On Line 111/117/123 the write completes before Line 112/118/124 invalidates cache. If cacheDelPattern fails, the method throws even though data is already persisted, which can cause retry-driven duplicate creates and integration inconsistency.

💡 Suggested fix
 export class ProfessorService {
+  private async invalidateProfessorCacheSafely() {
+    try {
+      await cacheDelPattern("professors:");
+    } catch (error) {
+      // Keep write-path successful; log and recover asynchronously if needed.
+      console.error("Professor cache invalidation failed", error);
+    }
+  }
+
   async create(data: any) {
     const record = await prisma.iitProfessor.create({ data });
-    await cacheDelPattern("professors:");
+    await this.invalidateProfessorCacheSafely();
     return record;
   }

   async update(id: number, data: any) {
     const record = await prisma.iitProfessor.update({ where: { id }, data });
-    await cacheDelPattern("professors:");
+    await this.invalidateProfessorCacheSafely();
     return record;
   }

   async delete(id: number) {
     const record = await prisma.iitProfessor.delete({ where: { id } });
-    await cacheDelPattern("professors:");
+    await this.invalidateProfessorCacheSafely();
     return record;
   }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async create(data: any) {
const record = await prisma.iitProfessor.create({ data });
await cacheDelPattern("professors:");
return record;
}
async update(id: number, data: any) {
const record = await prisma.iitProfessor.update({ where: { id }, data });
await cacheDelPattern("professors:");
return record;
}
async delete(id: number) {
const record = await prisma.iitProfessor.delete({ where: { id } });
await cacheDelPattern("professors:");
return record;
private async invalidateProfessorCacheSafely() {
try {
await cacheDelPattern("professors:");
} catch (error) {
// Keep write-path successful; log and recover asynchronously if needed.
console.error("Professor cache invalidation failed", error);
}
}
async create(data: any) {
const record = await prisma.iitProfessor.create({ data });
await this.invalidateProfessorCacheSafely();
return record;
}
async update(id: number, data: any) {
const record = await prisma.iitProfessor.update({ where: { id }, data });
await this.invalidateProfessorCacheSafely();
return record;
}
async delete(id: number) {
const record = await prisma.iitProfessor.delete({ where: { id } });
await this.invalidateProfessorCacheSafely();
return record;
}
🤖 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 `@server/src/module/professor/professor.service.ts` around lines 110 - 125, The
create/update/delete methods call prisma.iitProfessor.* and then await
cacheDelPattern("professors:"), which risks throwing after the DB commit; change
the cache invalidation to be non-fatal: call cacheDelPattern asynchronously and
handle its errors without bubbling them (e.g., fire-and-forget or wrap in
try/catch and only log failures) so that failures to delete cache never roll
back or surface after the DB write. Update the create, update, and delete
functions (references: create, update, delete methods and cacheDelPattern) to
ensure the DB operation result is returned even if cache invalidation fails.

@github-actions github-actions Bot added level:beginner Good for first-time contributors quality:clean Clean and well-structured contribution and removed level:intermediate Requires moderate project understanding quality:exceptional Exceptional implementation quality type:testing Adds or improves tests labels Jun 4, 2026
@github-actions github-actions Bot added quality:exceptional Exceptional implementation quality type:testing Adds or improves tests and removed quality:clean Clean and well-structured contribution labels Jun 4, 2026
@Sachinchaurasiya360
Copy link
Copy Markdown
Owner

Closing this PR. The cache invalidation approach is correct in principle, but the three new methods (create, update, delete) use untyped data: any parameters and there are no corresponding routes wired up to call them — adding dead service methods without routes creates confusion. Please open a fresh PR that includes the route wiring and proper TypeScript types for the data parameter. Thank you for the effort!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gssoc:approved Approved for GSSoC scoring gssoc level:beginner Good for first-time contributors quality:exceptional Exceptional implementation quality scope:backend Changes to server-side / API code type:bug Bug fixes type:performance Performance optimization changes type:testing Adds or improves tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: IIT Professor List and Stats Cache Invalidation on Modifications

2 participants