簡體   English   中英

Firebase函數如何在特定時間后從實時數據庫中刪除節點並從存儲中刪除文件

[英]Firebase Functions How to remove node from realtime database and file from storage after certain time

我是Firebase函數使用的新手。
7天后(以時間戳計算),我想從數據庫中刪除一個Post節點,然后,從Comment和Reaction中刪除所有引用該帖子的節點。 之后,如果帖子的photoVideoPath是Firebase Storage的引用,我想從我的存儲中刪除該對象。 我的數據庫結構是:

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

我究竟做錯了什么? 謝謝大家,祝你有美好的一天

您無需關注update()和remove()返回的承諾。 另外,您不能正確使用delete()返回的promise。 實時數據庫觸發器函數必須返回僅在函數中的所有其他異步工作完成后才能解析的承諾。

要了解有關如何將諾言與Cloud Functions結合使用的更多信息,請考慮按照此處的教程進行操作: https : //firebase.google.com/docs/functions/video-series/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM