Skip to content

Conversation

@Harish-Naruto
Copy link
Member

@Harish-Naruto Harish-Naruto commented Nov 21, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Replacing an existing image now removes the old file and always generates a new unique filename to avoid conflicts.
  • Tests

    • Updated tests to verify the removal of replaced images and the new unique-filename upload behavior.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 21, 2025

Walkthrough

uploadImage now always generates a UUID-based filename (preserving the original file extension) and, if a fileUrl is provided, deletes the existing image (via storage.remove) before uploading the new file; tests updated to expect UUID-named uploads and the removal call.

Changes

Cohort / File(s) Summary
Image upload logic
src/utils/imageUtils.ts
Always generate a UUID filename (keep original extension); remove prior filename-extraction-from-URL logic; when fileUrl is provided, call storage.delete/remove on the existing image before uploading the new file.
Tests for upload/delete behavior
tests/imageUtils.test.ts
Add/adjust mocks to include storage.remove returning { error: null }; update expectations to use a UUID-derived upload path (e.g., folder/test-uuid.png) and verify the previous image is removed when fileUrl is supplied.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant uploadImage as uploadImage()
    participant deleteImage as deleteImage()
    participant Storage

    User->>uploadImage: call with (file, fileUrl?)
    alt fileUrl provided
        rect `#E8F0FF`
            uploadImage->>deleteImage: delete(fileUrl)
            deleteImage->>Storage: remove(oldPath)
            Storage-->>deleteImage: { error: null } / removed
            deleteImage-->>uploadImage: deleted
        end
    end
    rect `#EFFFE8`
        uploadImage->>uploadImage: generate UUID + original extension -> filename
    end
    uploadImage->>Storage: upload(file, filename)
    Storage-->>uploadImage: uploaded -> publicUrl
    uploadImage-->>User: return publicUrl
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Check delete/remove error handling to avoid inconsistent state.
  • Verify filename generation preserves extensions in edge cases (no extension, query params).
  • Confirm tests accurately mock and assert the storage.remove call and UUID-based upload path.

Possibly related PRs

Suggested reviewers

  • callofcode07

Poem

🐰 I hop through code with tidy paws,
Old pictures cleared to follow laws.
UUID flowers bloom in their place,
A fresh new file, a cleaner space. 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'refactor image update logic in uploadImg function' accurately describes the main change—refactoring the image upload logic to always generate new UUIDs and delete existing images instead of reusing filenames.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch member-Profile-update-fix

📜 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 a51fb63 and e2ec074.

📒 Files selected for processing (1)
  • tests/imageUtils.test.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/imageUtils.test.ts

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.

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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/utils/imageUtils.ts (1)

76-78: Update test mock for storage.remove() in uploadImage test case.

The pipeline failure occurs in the test "uses existing filename from fileUrl if provided" (line 48–65). When uploadImage is called with a fileUrl, it invokes deleteImage, which expects storage.remove() to return { error, data }. However, the mock for remove is not configured in this test, causing it to return undefined and triggering a destructuring error.

Add the following line before calling uploadImage in that test:

storageMock.remove.mockResolvedValue({ error: null });
🧹 Nitpick comments (2)
src/utils/imageUtils.ts (2)

48-53: The upsert: true option is now redundant.

Since the filename is now always a fresh UUID, there's no scenario where you'd overwrite an existing file. The upsert option can be removed or set to false.

     .upload(filePath, file.buffer, {
       contentType: file.mimetype,
-      upsert: true,
     });

44-44: Remove redundant type annotation and fix spacing.

TypeScript automatically infers the string type from the template literal, making the explicit annotation unnecessary. Also, there's inconsistent spacing around the assignment operator.

-  const filename:string =  `${uuidv4()}.${ext}`;
+  const filename = `${uuidv4()}.${ext}`;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 22e59aa and d633a86.

📒 Files selected for processing (1)
  • src/utils/imageUtils.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/utils/imageUtils.ts (1)
src/app.ts (1)
  • supabase (12-15)
🪛 GitHub Actions: Run Tests
src/utils/imageUtils.ts

[error] 76-76: TypeError: Cannot destructure property 'error' of '(intermediate value)' as it is undefined during uploadImage test. Ensure the storage.remove call returns an object with an 'error' field.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tests/imageUtils.test.ts (1)

58-81: Update test name and verify deletion behavior.

The test name and comment (lines 58-59, 74) are outdated. The function now always generates a UUID-based filename rather than reusing the existing one. Additionally, the test doesn't verify that the old image is actually deleted when fileUrl is provided.

Apply this diff to update the test:

-    it("uses existing filename from fileUrl if provided", async () => {
-      // Simulate providing an existing URL so the helper extracts the filename
+    it("generates new UUID filename and deletes old image when fileUrl provided", async () => {
       const existingUrl =
         "https://xyz.supabase.co/storage/v1/object/public/images/folder/existing.png";
       storageMock.upload.mockResolvedValue({ error: null });
       storageMock.getPublicUrl.mockReturnValue({
         data: { publicUrl: "https://public.url/existing.png" },
       });
       storageMock.remove.mockReturnValue({error:null});
 
       const url = await uploadImage(
         mockSupabase as SupabaseClient,
         dummyFile,
         "folder",
         existingUrl,
       );
-      // Should use filename 'existing.png' instead of generating with uuid
+      // Should generate new UUID filename
       expect(storageMock.upload).toHaveBeenCalledWith(
         "folder/test-uuid.png",
         dummyFile.buffer,
         { contentType: dummyFile.mimetype, upsert: true },
       );
+      // Should delete the old image
+      expect(storageMock.remove).toHaveBeenCalledWith(["folder/existing.png"]);
       expect(url).toBe("https://public.url/existing.png");
     });
🧹 Nitpick comments (1)
src/utils/imageUtils.ts (1)

63-65: Race condition resolved; consider error handling for deletion.

The race condition from the previous review is now fixed—deletion occurs after successful upload, preventing data loss. However, if the deletion fails, the error is currently unhandled and the old image remains in storage.

Consider wrapping the deletion in a try-catch to log failures without blocking the upload flow:

   if (fileUrl) {
-    await deleteImage(supabase, fileUrl);
+    try {
+      await deleteImage(supabase, fileUrl);
+    } catch (error) {
+      // Log but don't fail - new image already uploaded
+      console.error("Failed to delete old image:", error);
+    }
   }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d633a86 and a51fb63.

📒 Files selected for processing (2)
  • src/utils/imageUtils.ts (2 hunks)
  • tests/imageUtils.test.ts (4 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/utils/imageUtils.ts (1)
src/app.ts (1)
  • supabase (12-15)

} else {
filename = `${uuidv4()}.${ext}`;
}
const filename:string = `${uuidv4()}.${ext}`;
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 | 🟡 Minor

Fix type annotation spacing.

The type annotation is missing a space after the colon, and there's an extra space before the equals sign.

Apply this diff to fix the formatting:

-  const filename:string =  `${uuidv4()}.${ext}`;
+  const filename: string = `${uuidv4()}.${ext}`;
📝 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
const filename:string = `${uuidv4()}.${ext}`;
const filename: string = `${uuidv4()}.${ext}`;
🤖 Prompt for AI Agents
In src/utils/imageUtils.ts around line 40, the const declaration's type
annotation has incorrect spacing; remove the extra space before the equals sign
and add a single space after the colon so the declaration uses standard spacing
for type annotations and assignment (i.e., make the colon followed by one space
and no space before =).

@Sherin-2711 Sherin-2711 merged commit 1e5ebcb into main Nov 21, 2025
2 checks passed
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.

3 participants