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

Viewed 2167

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

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

Related