react-admin-firebase icon indicating copy to clipboard operation
react-admin-firebase copied to clipboard

[feature-request] delete file on Firebase Storage when file is deleted on document

Open capsudo opened this issue 4 years ago • 3 comments

When a file is uploaded on react-admin, it is uploaded on Firebase Storage and the corresponding URL is added on the document on Firestore or Firebase RTDB.

When the file is deleted the URL field is removed from the document but the corresponding data on Firebase Storage remains.

It would be nice to have an option to automatically remove it because it can be an issue for big files ($$$).

capsudo avatar Jan 21 '22 17:01 capsudo

This is a great idea, I've actually done this on some other firebase systems, and shouldn't be too hard to implement.

Note to self: pseudo code when parsing document fields:

if (fieldIsAFile && fileHasBeenPreviouslyUploaded && fileIsNowDeleted && hasDeleteOnStorageFlag) {
  deleteFileFromStorageToo();
}

benwinding avatar Jan 24 '22 01:01 benwinding

I think the more traditional way to achieve this is to write a Cloud Function trigger that would delete the file when that field is deleted/erased from the document. This way you're also relying on Firebase directly to handle cleanup instead of a frontend client, which is inherently less reliable.

const handleFileDelete = functions.firestore
  .document('/collection/{doc}')
  .onWrite(async (change, context) => {
    const newDocument = change.after.data();
    const oldDocument = change.before.data();
    
    // Check if the file URL was deleted
    if (!newDocument?.fileUrl && oldDocument?.fileUrl) {
        // Delete file from Cloud Storage using Admin SDK
    }
}

https://firebase.google.com/docs/firestore/extend-with-functions#trigger_a_function_for_all_changes_to_a_document

5hee75 avatar Feb 25 '22 15:02 5hee75

Yes I think you are right, I should have thought about it.

In my case I replace a file with a new version so the fileURL is not deleted but the actual file on Firebase Storage is not, so I would need to handle this with a more complicated firebase function but this should be possible.

I will post it and close the issue when it is done.

capsudo avatar Feb 25 '22 15:02 capsudo