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:
- The function should be triggered when the user removes a Photo object from Firebase DB;
- 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"
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.