svkaka
svkaka

Reputation: 4022

Firebase Cloud functions remove orphan image from storage using url

In android I would simply call: FirebaseStorage.getInstance().getReferenceFromUrl(removeMe.getImgUrl()).delete(); to remove any file stored in firebase storage

That's how my index.js looks like now

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

exports.onDeleteTimelapse = functions.database.ref("/timelapses/{id}")
    .onDelete(event => {

        imagesRef.orderByChild("parentId")
            .equalTo(event.params.id)
            .on("value", function (snapshot) {
                snapshot.forEach(function (childSnapshot) {
                    //image url
                    //file name equals childSnapshot.val().id
                    var imgurl = childSnapshot.val().imgUrl;
                    //prints img url
                    console.log(imgurl + " ");
                    //todo remove <================
                    //remove img from dbs
                    childSnapshot.ref.remove();
                });
            });
    });

What's the way to achieve this behaviour using functions. imgurl is url where my image is stored

Upvotes: 0

Views: 409

Answers (1)

svkaka
svkaka

Reputation: 4022

Okay I fixed it, feel free o use it. U need to import

const gcs = require('@google-cloud/storage')();

exports.onDeleteTimelapse = functions.database.ref("/timelapses/{id}")
    .onDelete(event => {

        imagesRef.orderByChild("parentId")
            .equalTo(event.params.id)
            .on("value", function (snapshot) {
                snapshot.forEach(function (childSnapshot) {
                    childSnapshot.ref.remove(); //this calls method bellow
                });
            });
    });

exports.onDeleteImage = functions.database.ref("/images/{id}")
    .onDelete(event => {

        const filename = event.params.id;
        gcs
            .bucket(bucketName) // find it in Firebase>Storage>"gs://...." copy without gs 
             //or go to console.cloud.google.com/ buckets and copy name
            .file("images/" + filename) //file location in my storage
            .delete()
            .then(() => {
                console.log(`gs://${bucketName}/${filename} deleted.`);
            })
            .catch(err => {
                console.error('ERROR-DELETE:', err+ " filename: "+filename);
            });

    });

Upvotes: 1

Related Questions