lurning too koad
lurning too koad

Reputation: 2974

How to delete a Firebase Storage folder from a Firebase Cloud Function?

I couldn't find the deleteFiles() method in the Firebase API reference. My IDE tells me this method takes an optional DeleteFilesOptions argument and I couldn't find any information on that type as well. If someone could point me to this documentation I would appreciate it.

That said, I've seen a number of posts that use this method, with this argument, to delete an entire Storage folder (and all of its files) through a Cloud Function. My question is, is this the correct way to do it (since the documentation here is missing)?

const functions = require("firebase-functions");
const admin = require("firebase-admin");

exports.deleteStorageFolder = functions.https.onCall(async (data, _context) => {
    const uid = data.userId;

    try {
        const bucket = admin.storage().bucket(); // returns the default bucket, which is good
        await bucket.deleteFiles({
            prefix: `images/users/${uid}`, // the path of the folder
        });
        return Promise.resolve(true);
    } catch (error) {
        throw new functions.https.HttpsError("unknown", "Failed to delete storage folder.", error);
    }
});

Upvotes: 1

Views: 3254

Answers (1)

RJC
RJC

Reputation: 1338

As @Doug already mentioned in the comment, "Firebase just provides wrappers around Cloud Storage. They are the same thing.". Also, according to this documentation, "Cloud Storage for Firebase stores your files in a Google Cloud Storage bucket, making them accessible through both Firebase and Google Cloud. This allows you the flexibility to upload and download files from mobile clients via the Firebase SDKs for Cloud Storage."

Having been said that, I've tried replicating the code snippet you've provided using deleteFiles(), and it worked fine on my end:

// // The Firebase Admin SDK to access Firestore.
const functions = require("firebase-functions");
const admin = require('firebase-admin');

const firebaseConfig = {
    // Your Firebase configuration...
};

admin.initializeApp(firebaseConfig);

const bucket = admin.storage().bucket();
async function deleteFolder(){
    await bucket.deleteFiles({
    prefix: `images/users/${uid}`   // the path of the folder
    });
}

deleteFolder();

One another option that you can do is to directly use Google Cloud Storage, and skip using the Firebase Storage:

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket("your-bucket-name");

bucket.deleteFiles({
  prefix: `images/users/${uid}`
}, function(err) {
  if (!err) {
    console.log("All files in the `images` directory have been deleted.");    
  }
});

Just a note, following the suggestion of Doug, you can try and test it out first in your local or test environment. For further reference, you can refer to delete() and deleteFiles()

Upvotes: 5

Related Questions