Odai A. Ali
Odai A. Ali

Reputation: 1235

how to create refFromURL with admin privilege on cloud functions?

I want to have a reference to an image using its http URL when firestore update cloud function triggered so that i can take the url from change provide by onUpdate() function and use it to get a reference to the image on firebase storage and delete it.

Upvotes: 1

Views: 717

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83163

In order to delete a file stored in Cloud Storage for Firebase from a Cloud Function you will need to create a File object based on:

  1. The Bucket instance this file is attached to;

  2. The name of the file,

and then call the delete() method

as detailed in the Node.js library documentation https://cloud.google.com/nodejs/docs/reference/storage/2.0.x/File.

Here is an example of code from the documentation:

const storage = new Storage();
const bucketName = 'Name of a bucket, e.g. my-bucket';
const filename = 'File to delete, e.g. file.txt';

// Deletes the file from the bucket
storage
  .bucket(bucketName)
  .file(filename)
  .delete()
  .then(() => {
    console.log(`gs://${bucketName}/${filename} deleted.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

From your question, I understand that your app clients don't have the bucket and file names as such and only have a download URL (probably generated through getDownloadURL if it is a web app, or the similar method for other SDKs).

So the challenge is to derive the bucket and file names from a download URL.

If you look at the format of a download URL you will find that it is composed as follows:

https://firebasestorage.googleapis.com/v0/b/<your-project-id>.appspot.com/o/<your-bucket-name>%2F<your-file-name>?alt=media&token=<a-token-string>

So you just need to use a set of Javascript methods like indexOf(), substring() and/or slice() to extract the bucket and file names from the download URL.

Based on the above, your Cloud Function code could then look like:

const storage = new Storage();

.....

exports.deleteStorageFile = functions.firestore
    .document('deletionRequests/{requestId}')
    .onUpdate((change, context) => {
      const newValue = change.after.data();
      const downloadUrl = newValue.downloadUrl;

      // extract the bucket and file names, for example through two dedicated Javascript functions
      const fileBucket = getFileBucket(downloadUrl);
      const fileName = getFileName(downloadUrl);

      return storage
        .bucket(fileBucket)
        .file(fileName)
        .delete()

    }); 

Upvotes: 1

Related Questions