Rene Alas
Rene Alas

Reputation: 541

Delete Folder inside Firebase Storage with Cloud Functions

I want to create a Cloud Function that when an Object (Listing) is deleted in Firestore, it automatically deletes the images associated in FirebaseStorage.

As Context, when a Listing is created we take that Document Id and set it as the name of a subfolder in FirebaseStorage.

Like this:

Folder Structure

So basically I have the Main Bucket inside a Folder Call ListingImages and Inside per Listing (document in Firestore), there is a Folder.

So my end goal is that when I delete the document with that ID in my Firestore, it deletes the Folder in Firebase Storage and all its content.

Currently, I have this Cloud Function Code but it doesn't work:

// Function que elimina imagenes de un Listing cuando es borrado de Firebase.
exports.listingImagesDelete = functions.firestore.document("listings/{listingId}").onDelete((snapshot, context) => {
  const listingId = snapshot.id;

  const filePath = "ListingImages/" + listingId + "/";
  const defaultBucket = admin.storage().bucket();
  const file = defaultBucket.file(filePath);
  const pr = file.delete();

  return pr;
});

But when I run it (Delete the listing from Firestore) it gives me this Error:

Error on Function Running

It looks as if there is no Object there, although there is a Folder.

Any ideas on how to accomplish this task?

Upvotes: 1

Views: 1034

Answers (2)

Dharmaraj
Dharmaraj

Reputation: 50840

You can try using @google-cloud/storage module and setting the path prefix:

const { Storage } = require("@google-cloud/storage")

exports.listingImagesDelete = functions.firestore.document("listings/{listingId}").onDelete((snapshot, context) => {
  const listingId = snapshot.id;
  
  const storage = new Storage();

  const bucket = storage.bucket('name'); // [PROJECT_ID].appspot.com is default bucket
    
  return bucket.deleteFiles({
    prefix: `ListingImages/${listingId}`
  })
});

Upvotes: 5

Frank van Puffelen
Frank van Puffelen

Reputation: 598775

Folders are not a real thing on Cloud Storage. In reality it is just one long list of files, and having a / in the name/path of the file is interpreted as a folder (also referred to as a prefix, since it's the start of the name/path).

What this means in practice is that in order to delete a folder, you need to delete all files inside that folder. Once you do that, the folder will automatically disappear.

Upvotes: 2

Related Questions