I want to use a cloud function background trigger, so when I delete a user data in Firestore, I want to also delete their profile picture in the Firebase storage.
the userID is used as the image name of that picture. and the image is located inside the profilepicture folder
export const removeProfilePictureWhenDeletingUserData = functions.firestore
.document('userss/{userID}')
.onDelete((snap, context) => {
const userID = context.params.userID
// how to delete the image in here?
});
I have tried to read the documentation, but I am confused about how to implement that method :(. really need your help. thanks in advance
Using refFromURL() , we can get the image reference from Firebase Storage of the image we want to delete. Then use . delete() to delete the image from Firebase. Finally, we remove that URL from our allImages array.
Delete files from FirebaseUsing refFromURL() , get the image reference from Firebase Storage of the image that should be deleted. Then use . delete() to delete the image from Firebase. Finally, remove that URL from the allImages array.
The following Cloud Function code will do the job.
// Adapted following Doug's advice in his comment //
....
const admin = require('firebase-admin');
admin.initializeApp();
....
var defaultStorage = admin.storage();
exports.removeProfilePictureWhenDeletingUserData = functions.firestore
.document('users/{userID}')
.onDelete((snap, context) => {
const userID = context.params.userID;
const bucket = defaultStorage.bucket();
const file = bucket.file('profilePicture/' + userID + '.png');
// Delete the file
return file.delete();
});
See the following doc items for more detail:
https://firebase.google.com/docs/reference/admin/node/admin.storage.Storage
https://cloud.google.com/nodejs/docs/reference/storage/1.7.x/File#delete
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With