Skip to content

Conversation

@samrth07
Copy link
Collaborator

@samrth07 samrth07 commented Jul 27, 2025

increase the size of image as well as the add auto update and delete functionality of storage image

Summary by CodeRabbit

  • New Features

    • Images are now deleted from storage when a project or achievement is removed.
    • Updating a project or achievement image now replaces the old image in storage.
  • Bug Fixes

    • Improved handling of missing project IDs during updates, ensuring proper error reporting.
    • Corrected the retrieval of deployment URLs during project creation.
  • Documentation

    • Updated API documentation for topic creation responses to reflect the current response structure.
  • Refactor

    • Code formatting and naming improvements for consistency and clarity in project routes.
  • Tests

    • Extended tests to verify proper deletion of images when achievements or projects are removed.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 27, 2025

Walkthrough

This update introduces image deletion and improved image update handling in both project and achievement controllers. When deleting or updating projects or achievements, the associated image is now properly deleted or replaced. Tests are updated to mock and verify image deletion. Additional changes include minor code cleanup and improved API documentation formatting.

Changes

File(s) Change Summary
src/controllers/project.controller.ts Added image deletion on project removal and improved image update logic to replace existing images.
src/controllers/achievement.controller.ts Added image deletion on achievement removal and improved image update logic to replace existing images.
tests/Project.test.ts, tests/Achievement.test.ts Extended mocks to include deleteImage and added assertions verifying image deletion logic in tests.
src/routes/projects.ts Renamed middleware, reformatted imports and comments, minor refactor; no functional changes.
src/routes/index.ts Removed extraneous blank line; stylistic only.
src/routes/topics.ts Updated API documentation for POST /topics response; no implementation changes.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Controller
    participant Service
    participant ImageUtils

    %% Project/Achievement Deletion Flow
    Client->>Controller: DELETE /projects/:id or /achievements/:id
    Controller->>Service: getProjectById(id) or getAchievementById(id)
    Service-->>Controller: Project/Achievement (with imageUrl)
    alt imageUrl exists
        Controller->>ImageUtils: deleteImage(req, imageUrl)
        ImageUtils-->>Controller: (image deleted)
    end
    Controller->>Service: deleteProjectById(id) or deleteAchievementById(id)
    Service-->>Controller: (deleted)
    Controller-->>Client: 200 OK

    %% Project/Achievement Update Flow (with image)
    Client->>Controller: PATCH /projects/:id or /achievements/:id (with file)
    Controller->>Service: getProjectById(id) or getAchievementById(id)
    Service-->>Controller: Project/Achievement (with imageUrl)
    Controller->>ImageUtils: uploadImage(req, oldImageUrl)
    ImageUtils-->>Controller: newImageUrl
    Controller->>Service: updateProjectById(id, newImageUrl, ...)
    Service-->>Controller: updated entity
    Controller-->>Client: 200 OK
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15–20 minutes

Possibly related PRs

Suggested reviewers

  • i-am-that-guy
  • Harish-Naruto

Poem

A hop and a skip, some images gone,
Projects and achievements, their old files withdrawn.
With careful new logic, the carrots align,
Deletion and updates now work just fine!
🥕✨

— A code rabbit, cleaning up the vine

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d2b016f and df481bd.

📒 Files selected for processing (1)
  • src/routes/topics.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/routes/topics.ts
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch minor-changes

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
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: 3

🧹 Nitpick comments (1)
src/routes/projects.ts (1)

15-26: Consider retaining error logging for better debugging.

The middleware rename from parseCreateProjectData to parseProjectData is good for broader applicability. However, removing the error logging on JSON parse failure might make debugging more difficult.

Consider adding back error logging while keeping the clean response:

    } catch (e) {
+     console.error('JSON parse error in projectData:', e);
      return res.status(400).json({ message: 'Invalid JSON in projectData field' });
    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f775c32 and 12835c4.

📒 Files selected for processing (5)
  • src/app.ts (1 hunks)
  • src/controllers/project.controller.ts (4 hunks)
  • src/routes/index.ts (0 hunks)
  • src/routes/projects.ts (3 hunks)
  • src/routes/topics.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • src/routes/index.ts
🧰 Additional context used
🪛 GitHub Actions: Run Tests
src/controllers/project.controller.ts

[error] 92-92: TypeError: (0 , imageUtils_1.deleteImage) is not a function. This error occurred during the test 'deleteProjectRoutes › should return 200 if project deleted' in tests/Project.test.ts.

🔇 Additional comments (6)
src/app.ts (1)

35-35: LGTM: File size limit increase supports larger image uploads.

The increase from 2MB to 5MB aligns with the PR objectives to enhance image handling capabilities. This is a reasonable limit for project images while maintaining security controls.

src/routes/projects.ts (2)

2-2: LGTM: Import formatting improvements.

The consistent formatting and spacing of imports improves code readability and maintainability.

Also applies to: 5-13


34-64: LGTM: API documentation formatting improvements.

The consistent indentation and formatting of API documentation comments improves readability and maintainability.

src/controllers/project.controller.ts (3)

42-42: LGTM: Fixed deployUrl source path.

Correctly changed from req.body.deployUrl to req.body.projectData.deployUrl to match the expected data structure.


73-73: LGTM: Simplified validation logic.

Removing the redundant !projectId check is appropriate since it's already validated earlier in the function.


88-94: LGTM: Added image cleanup on project deletion.

The logic to delete associated images when removing projects is a good practice for resource management, assuming the deleteImage function works correctly.

import { Request, Response } from "express";
import { ApiError } from "../utils/apiError";
import { uploadImage } from "../utils/imageUtils";
import { deleteImage, uploadImage } from "../utils/imageUtils";
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify deleteImage function export and implementation.

The pipeline failure indicates that deleteImage is not a function. This suggests the function is either not exported from ../utils/imageUtils or doesn't exist.


🏁 Script executed:

#!/bin/bash
# Verify deleteImage function exists and is properly exported
echo "Checking if deleteImage function exists in imageUtils:"
ast-grep --pattern 'export $_ deleteImage'
echo "Checking function declarations:"
ast-grep --pattern 'function deleteImage($_) { $$$ }'
ast-grep --pattern 'const deleteImage = $_'

Length of output: 338


Implement and Export deleteImage in src/utils/imageUtils.ts

The import in src/controllers/project.controller.ts is failing at runtime because deleteImage isn’t defined or exported. Please:

  • In src/utils/imageUtils.ts, add and export the deleteImage function. For example:
    export async function deleteImage(imageUrl: string): Promise<void> {
      // your deletion logic here
    }
  • Verify that the file path in the controller matches the utils file location.
  • Fix the typo on line 64 in the controller: change “File is not exits” → “File does not exist”.
  • Rename the fileUlr variable to fileUrl for clarity.
🤖 Prompt for AI Agents
In src/utils/imageUtils.ts around the top of the file, implement and export an
async function named deleteImage that accepts an imageUrl string parameter and
contains the logic to delete the image. Then, in
src/controllers/project.controller.ts, ensure the import path for deleteImage
matches the utils file location exactly. Also, on line 64 of the controller,
correct the typo in the error message from "File is not exits" to "File does not
exist" and rename the variable fileUlr to fileUrl for clarity and correctness.

Comment on lines +59 to 66
if( !projectId ) throw new ApiError("ProjectId is missng !!!" , 401);

if (file) {
imageUrl = await uploadImage(supabase, file, 'projects');
if ( file ) {
const response = await projectService.getProjectById(projectId);
const fileUlr = response?.imageUrl;
if( !fileUlr ) throw new ApiError("File is not exits");
imageUrl = await uploadImage(supabase, file, 'projects' , fileUlr);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typos and improve error handling.

Several issues need attention:

  1. Line 63: Variable name fileUlr should be fileUrl
  2. Line 64: Error message should be more descriptive
  3. Missing error status code on line 64
  if ( file ) {
    const response = await projectService.getProjectById(projectId);
-   const fileUlr = response?.imageUrl;
+   const fileUrl = response?.imageUrl;
-   if( !fileUlr ) throw new ApiError("File is not exits");
+   if( !fileUrl ) throw new ApiError("Existing image not found", 404);
-   imageUrl = await uploadImage(supabase, file, 'projects' , fileUlr);
+   imageUrl = await uploadImage(supabase, file, 'projects' , fileUrl);
  }
📝 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
if( !projectId ) throw new ApiError("ProjectId is missng !!!" , 401);
if (file) {
imageUrl = await uploadImage(supabase, file, 'projects');
if ( file ) {
const response = await projectService.getProjectById(projectId);
const fileUlr = response?.imageUrl;
if( !fileUlr ) throw new ApiError("File is not exits");
imageUrl = await uploadImage(supabase, file, 'projects' , fileUlr);
}
if( !projectId ) throw new ApiError("ProjectId is missng !!!" , 401);
if ( file ) {
const response = await projectService.getProjectById(projectId);
const fileUrl = response?.imageUrl;
if( !fileUrl ) throw new ApiError("Existing image not found", 404);
imageUrl = await uploadImage(supabase, file, 'projects' , fileUrl);
}
🤖 Prompt for AI Agents
In src/controllers/project.controller.ts around lines 59 to 66, correct the typo
by renaming the variable 'fileUlr' to 'fileUrl'. Improve the error message on
line 64 to be more descriptive, such as "File does not exist for the given
project", and add an appropriate HTTP status code (e.g., 404) to the ApiError
thrown there for consistent error handling.

Copy link
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)
src/controllers/achievement.controller.ts (1)

98-121: Excellent logic restructuring with minor formatting issue.

The restructured flow is much better:

  1. Validates existence before processing
  2. Properly handles image replacement by passing existing URL
  3. Includes uploaded image in field validation

However, there's an indentation issue that affects readability.

Fix the indentation for better code consistency:

-    if (
-      !title &&
-      !description &&
-      !achievedAt &&
-      !imageUrl &&
-      (!Array.isArray(memberIds) || memberIds.length === 0)
-    ) {
-      throw new ApiError("At least one field must be provided for update", 400);
-    }
+  if (
+    !title &&
+    !description &&
+    !achievedAt &&
+    !imageUrl &&
+    (!Array.isArray(memberIds) || memberIds.length === 0)
+  ) {
+    throw new ApiError("At least one field must be provided for update", 400);
+  }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5c0925c and 216a703.

📒 Files selected for processing (1)
  • src/controllers/achievement.controller.ts (3 hunks)
🧰 Additional context used
🪛 GitHub Actions: Run Tests
src/controllers/achievement.controller.ts

[error] 151-151: TypeError: (0 , imageUtils_1.deleteImage) is not a function. This error occurred during the test 'deleteAchievementById › should delete the achievement and return 200 success message' in the test suite 'tests/Achievement.test.ts'.

🔇 Additional comments (1)
src/controllers/achievement.controller.ts (1)

145-153: Excellent addition of proper resource cleanup and validation.

The added logic significantly improves the delete operation by:

  1. Validating achievement existence before deletion (prevents unnecessary operations)
  2. Properly cleaning up associated images to prevent storage bloat
  3. Providing appropriate 404 errors for missing resources

This follows best practices for resource management and maintains data consistency.

import { Request, Response } from "express";
import * as achievementService from "../services/achievement.service";
import { uploadImage } from "../utils/imageUtils";
import { uploadImage, deleteImage } from "../utils/imageUtils";
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify deleteImage function exists and is properly exported.

The pipeline failure indicates deleteImage is not a function, suggesting either the function doesn't exist in the imageUtils module or isn't properly exported.

Let me verify the imageUtils implementation:


🏁 Script executed:

#!/bin/bash
# Check if deleteImage function exists and is properly exported
cat src/utils/imageUtils.ts | grep -A 10 -B 2 "deleteImage"

# Also check if there are any export issues
rg "export.*deleteImage" src/utils/

Length of output: 447


I want to inspect the full imageUtils.ts to confirm all exports and see if a default export or other export styles might be conflicting with how tests import/mocking it.


🏁 Script executed:

#!/bin/bash
# Display the first 200 lines of imageUtils.ts to verify export patterns
sed -n '1,200p' src/utils/imageUtils.ts

Length of output: 2363


Controller import is correct; update your tests’ mocks for deleteImage

The deleteImage function is properly defined and exported in src/utils/imageUtils.ts. The runtime error in your pipeline (“deleteImage is not a function”) indicates that your test suite’s mock of the imageUtils module doesn’t include a deleteImage stub. To resolve:

• Locate your Jest manual mock for src/utils/imageUtils (e.g., in __mocks__/src/utils/imageUtils.ts).
• Add or export a mock implementation for deleteImage, for example:

export const deleteImage = jest.fn(async () => {});

• Ensure both uploadImage and deleteImage are exported in that mock.

With your mocks updated, the controller import will work as expected and the tests should pass.

🤖 Prompt for AI Agents
In src/controllers/achievement.controller.ts at line 3, the import of
deleteImage is correct, but your Jest manual mock for src/utils/imageUtils is
missing a mock implementation for deleteImage, causing runtime errors in tests.
To fix this, locate the Jest manual mock file for src/utils/imageUtils (usually
in __mocks__/src/utils/imageUtils.ts) and add an exported mock function for
deleteImage, such as export const deleteImage = jest.fn(async () => {}); also
ensure uploadImage is exported in the mock. This will align the mock with the
actual module exports and resolve the test errors.

@Harish-Naruto Harish-Naruto merged commit 06b2167 into main Jul 27, 2025
1 of 2 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Jul 29, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants