Firebase function to delete file from storage when deleting object from database using NodeJS

I am new to NodeJS and I am trying to write the following method for Cloud Functions for Firebase.

What I am trying to achieve:

  • The function should run when the user deletes the Photo object from the Firebase database;
  • The code should delete the file object from storage corresponding to the Photo object.

This is my Firebase DB structure:

photos / {userUID} / {photoUID}

{
"dateCreated":      "2017-07-27T16:40:31.000000Z",
"isProfilePhoto":   true,
"isSafe":           true,
"uid":              "{photoUID}",
"userUID":          "{userUID}"
}

      

And the Firebase storage format:

photos / {userUID} / {photoUID} .png

And the NodeJS code I'm using:

    const functions = require('firebase-functions')
    const googleCloudStorage = require('@google-cloud/storage')({keyFilename: 'firebase_admin_sdk.json' })
    const admin = require('firebase-admin')
    const vision = require('@google-cloud/vision')();

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

    exports.sanitizePhoto = functions.database.ref('photos/{userUID}/{photoUID}')
        .onDelete(event => {

            let photoUID = event.data.key
            let userUID = event.data.ref.parent.key

            console.log(`userUID: ${userUID}, photoUID: ${photoUID}`);

            if (typeof photoUID === 'undefined' || typeof userUID === 'undefined') {
                console.error('Error while sanitize photo, user uid or photo uid are missing');
                return
            }

            console.log(`Deleting photo: ${photoUID}`)

            googleCloudStorage.bucket(`photos/${userUID}/${photoUID}.png`).delete().then(() => {
                console.log(`Successfully deleted photo with UID: ${photoUID}, userUID : ${userUID}`)
            }).catch(err => {
                console.log(`Failed to remove photo, error: ${err}`)
            });

        });

      

While running it, I get the following error: "ApiError: Not found"

enter image description here

I think this piece of code is the one causing the problem:

googleCloudStorage.bucket(`photos/${userUID}/${photoUID}.png`).delete()

      

Thanks in advance for your support and patience.

+3


source to share


2 answers


Found the problem, here is the code that works for me:



exports.sanitizePhoto = functions.database.ref('photos/{userUID}/{photoUID}')
    .onDelete(event => {

        let photoUID = event.data.key
        let userUID = event.data.ref.parent.key

        console.log(`userUID: ${userUID}, photoUID: ${photoUID}`);

        if (typeof photoUID === 'undefined' || typeof userUID === 'undefined') {
            console.error('Error while sanitize photo, user uid or photo uid are missing');
            return
        }

        console.log(`Deleting photo: ${photoUID}`)

        const filePath = `photos/${userUID}/${photoUID}.png`
        const bucket = googleCloudStorage.bucket('myBucket-91823.appspot.com')
        const file = bucket.file(filePath)

        file.delete().then(() => {
            console.log(`Successfully deleted photo with UID: ${photoUID}, userUID : ${userUID}`)
        }).catch(err => {
            console.log(`Failed to remove photo, error: ${err}`)
        });

    });

      

+3


source


try the code

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

    const fileBucketPush = 'Storage bucket.appspot.com'; // The Storage bucket that contains the file.
    const filePathPush = 'folder/'+nameImage; // File path in the bucket.
    vision.detectSafeSearch(gcs.bucket(fileBucketPush).file(filePathPush))
      .then((results) => {
       ..///

      })
      .catch((err) => {
        console.error('ERROR:', err);
      });

      



Enable Cloud Vision API?

+1


source







All Articles