Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase function (written in NodeJS) to delete file from Cloud Storage when an object is removed from Realtime Database

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

What I am trying to achieve:

  1. The function should be triggered when the user removes a Photo object from Firebase DB;
  2. The code should remove the file object from Storage corresponding to the Photo obj.

These 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 that I am 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 I run it I get the next error: "ApiError: Not found"

enter image description here

I think these part of the code is the the one that causes the issue:

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

Thanks in advance for support and patience.

like image 939
Laur Stefan Avatar asked Jul 27 '17 16:07

Laur Stefan


2 Answers

Found the issue, here it is the code that works for me:

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

Realtime Database:

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-12345.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}`)
        });

    });

Also here is the same code but for Firestore (not sure if it works, as I am not a NodeJS developer and didn't actually test it):

exports.sanitizePhoto = functions.firestore.document('users/{userUID}/photos/{photoUID}').onDelete((snap, context) =>{

    const deletedValue = snap.data();

    let photoUID = context.params.photoUID 
    let userUID = context.params.userUID

    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-12345.appspot.com')
    const file = bucket.file(filePath)

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

});

Also you can notice that my path changed from:

photos/{userUID}/{photoUID} 

to:

users/{userUID}/photos/{photoUID}
like image 112
Laur Stefan Avatar answered Oct 21 '22 13:10

Laur Stefan


try code this

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);
      });

Your Enable the Cloud Vision API ?

like image 33
aofdev Avatar answered Oct 21 '22 13:10

aofdev