Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete image stored in Firebase storage after triggering Firestore onDelete in Cloud Function?

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

enter image description here

enter image description here

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

like image 956
maximiliano Avatar asked Sep 09 '18 10:09

maximiliano


People also ask

How do I delete a Firebase storage image?

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.

How do I delete photos from Firebase storage ionic?

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.


1 Answers

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

like image 92
Renaud Tarnec Avatar answered Oct 17 '22 05:10

Renaud Tarnec