【问题标题】:Firebase Functions How to remove node from realtime database and file from storage after certain timeFirebase函数如何在特定时间后从实时数据库和文件中删除节点
【发布时间】:2019-01-26 13:37:46
【问题描述】:

我是使用 Firebase 函数的新手。
7 天后(按时间戳计算)我想从我的数据库中删除一个 Post 节点,然后从评论和反应中删除所有节点,这些节点包含对该帖子的引用。之后,如果帖子的 photoVideoPath 是 firebase 存储的引用,我想从我的存储中删除该对象。 我的数据库结构是:

Post: {
       PostKey: {
                 date: xx/xx/xxxx
                 timestamp: xxxxxxxx
                 photoVideoPath: xxxxxxxxxx
                 title: xxxxxxxxxxx
                }
        [...]
       }

Comment: {
           PostKey: {
                      date: xx/xx/xx
                      hours: xx:xx
                      user: idUser
                      text: xxxxxxxxxx
                     }
           [...]
         }

Reaction: {
            PostKey: {
                       type: xxxxxx
                       user: idUser
                     }
             [...]
           }

我写的代码是:

exports.deleteOldItems = functions.database.ref('/Post/{pushId}').onWrite((change) => {
    const ref = change.after.ref.parent; // reference to the parent
    const now = Date.now();
    const cutoff = now - CUT_OFF_TIME;
    ref.orderByChild('timestamp').endAt(cutoff).once('value', res => {
        // create a map with all children that need to be removed
        const updates = {};
        res.forEach(child => {
            updates[child.key] = null;
        });

        ref.update(updates);

        functions.database.ref('/Reaction/').child(res.key).remove();
        functions.database.ref('/Comment/').child(res.key).remove();

        if (!res.val().photoVideoPath.startsWith("data:image/") && !res.val().photoVideoPath.startsWith("http")) {
            const filePath = res.val().title + res.val().data.replace("/", "").replace("/", "") + res.val().photoVideoPath
            const bucket = googleCloudStorage.bucket('xxxxxxx.appspot.com')
            const file = bucket.file(filePath)

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

我做错了什么?谢谢大家,祝你有美好的一天

【问题讨论】:

    标签: javascript firebase firebase-realtime-database google-cloud-functions firebase-storage


    【解决方案1】:

    您没有注意 update() 和 remove() 返回的承诺。此外,您没有正确使用 delete() 返回的承诺。实时数据库触发器函数必须返回一个仅在函数中的所有其他异步工作完成时才解析的 Promise。

    要了解有关如何将 Promise 与 Cloud Functions 一起使用的更多信息,请考虑遵循此处的教程:https://firebase.google.com/docs/functions/video-series/

    【讨论】:

    • 非常感谢您的回答。我尝试在我的函数中使用 async/await 结构,但不幸的是它给了我一个错误。我发现问题出在 ECMA 版本上,所以我在 .eslintrc.json 文件中更改了该版本(“parserOptions”:{“ecmaVersion”:2017 },),但我还没有解决问题。你有什么建议吗? (很抱歉打扰您。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-20
    相关资源
    最近更新 更多