【发布时间】:2018-01-03 12:19:26
【问题描述】:
我是 NodeJS 的新手,我正在尝试为 Cloud Functions for Firebase 编写下一个方法。
我想要达到的目标:
- 当用户从 Firebase DB 中移除照片对象时,该函数应该被触发;
- 代码应从 Storage 中删除与 Photo obj 对应的文件对象。
这些是我的 Firebase 数据库结构:
照片/{userUID}/{photoUID}
{
"dateCreated": "2017-07-27T16:40:31.000000Z",
"isProfilePhoto": true,
"isSafe": true,
"uid": "{photoUID}",
"userUID": "{userUID}"
}
以及 Firebase 存储格式:
照片/{userUID}/{photoUID}.png
以及我正在使用的 NodeJS 代码:
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}`)
});
});
当我运行它时,我得到下一个错误:“ApiError: Not found”
我认为这部分代码是导致问题的原因:
googleCloudStorage.bucket(`photos/${userUID}/${photoUID}.png`).delete()
提前感谢您的支持和耐心。
【问题讨论】:
-
@Jay 我做了必要的更改。
标签: node.js firebase firebase-realtime-database firebase-storage google-cloud-functions