Search code examples
javascriptfirebasegoogle-cloud-platformfirebase-realtime-databasegoogle-cloud-storage

Delete file in cloud storage from cloud functions


I'm trying to make a Google Cloud Function which deletes images linked to person object in Firebase realtime database.. But every time I'm getting "Error during request" error (without any specific error.code, it's just undefined).. Here is a function code:

const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
const gcs = require('@google-cloud/storage')({ 
  projectId: "PROJ_ID",
  keyFilename: "SERV_ACC.json LOCATED IN FUNCTIONS FOLDER"});

admin.initializeApp(functions.config().firebase);

exports.removePersonImage = 
functions.database.ref("users/{userId}/persons/{personId}")
 .onDelete((snapshot, context) => {
   const person = snapshot.val();    

   if (!person.photo || !person.photo.key) {
    console.log("Person doesn't have photo");
    return true;
   }

   var path = "user/" + context.params.userId + "/" + person.photo.key + ".jpg";

   console.log("Bucket path: " + path);

   return gcs.bucket(path)
    .delete()
    .then(() => {
      console.log("Image " + person.photo.key + " successfully deleted");
      return true;
    })
    .catch(err => {
      console.error("Failed to remove image " + person.photo.key);
      console.error("Error: " + err.message);
      return false;
    });
});

Solution

  • I think you are getting the reference to a Bucket with the path of a File.

    You should first create a reference to your Bucket and then use the file() method on the Bucket to create the File object.

    First declare the bucket from the root bucket name you see in the Storage console but without gs://, as follows:

    const bucket = gcs.bucket("***projectname***.appspot.com");  
    

    Then declare your file with the the "directories".

    const file = bucket.file("user/" + context.params.userId + "/" + person.photo.key + ".jpg");
    

    Then call delete:

    return file.delete()
        .then(() => {
        ....
    

    See https://cloud.google.com/nodejs/docs/reference/storage/1.7.x/Bucket#file

    and https://cloud.google.com/nodejs/docs/reference/storage/1.7.x/Storage#bucket