[feature-request] delete file on Firebase Storage when file is deleted on document
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 ($$$).
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();
}
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
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.