Search code examples
node.jsfirebasegoogle-cloud-platformgoogle-cloud-functionsgoogle-cloud-storage

how to delete image in firebase storage using cloud function?


so I have a firestore trigger function written using nodeJS, when a document in firestore is deleted, then I also want to delete the image stored in Firebase storage, the name of the file in storage is the same as the deleted document ID. here is my function:

const functions = require('firebase-functions')

// initialize firestore database
const admin = require("../utilities/firebase_admin_init")
const db = admin.firestore()
const storage = admin.storage()

// firestore reference
const eventRef = db.collection('events')

exports.firestoreDeleteEventCleanUp = functions.firestore.document('events/{eventId}').onDelete((snapshot,context) => {

    const eventID = context.params.eventId

    // how to delete the image in firebase storage in here ????

})

and the admin initialization

const admin = require("firebase-admin")
const functions = require('firebase-functions')
admin.initializeApp(functions.config().firebase)

module.exports = admin

in Android, I can do this to delete image in storage

// Create a storage reference from our app
val storageRef = storage.reference

// Create a reference to the file to delete
val desertRef = storageRef.child("images/desert.jpg")

// Delete the file
desertRef.delete().addOnSuccessListener {
    // File deleted successfully
}.addOnFailureListener {
    // Uh-oh, an error occurred!
}

but now I am using admin SDK, and I don't know how to delete that file using admin SDK. I have tried to read the documentation in here https://firebase.google.com/docs/storage/admin/start . but I don't know what to do to delete the image in firebase storage like the image below

what is the equivalent of storageRef.child("images/desert.jpg") if using firestore trigger ?

enter image description here


Solution

  • As explained in the documentation item you refer to, the "Firebase Admin SDK depends on the Google Cloud Storage client libraries to provide Cloud Storage access." You should use the Node.js Client Google Cloud Storage.

    In particular, you need to use the bucket() method of Storage and the delete() method of File, as follows:

    const functions = require('firebase-functions')
    const admin = require('firebase-admin');
    
    admin.initializeApp();
    
    const db = admin.firestore()  // <- actually this is not needed for the CF below
    const storage = admin.storage()
    
    exports.firestoreDeleteEventCleanUp = functions.firestore.document('events/{eventId}').onDelete((snapshot,context) => {
    
        const eventID = context.params.eventId
    
        const defaultBucket = storage.bucket(); 
        const file = defaultBucket.file("eventThumbnail/" + eventID);
    
        return file.delete();
    
    });