Firebase Cloud Functions 会在删除节点后立即删除节点,而不是 24 小时后

2024-03-28

我的目标是在使用 Firebase Cloud Functions 和实时数据库发送消息节点 24 小时后删除所有消息节点。我尝试复制并粘贴答案这个帖子 https://stackoverflow.com/questions/32004582/delete-firebase-data-older-than-2-hours然而,出于某种原因,消息在创建后会立即删除,而不是 24 小时后。如果有人能帮助我解决这个问题,我将非常感激。我根据同一问题尝试了多个不同的答案,但它们对我不起作用。

这是我的 index.js 文件:

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

// Cut off time. Child nodes older than this will be deleted.
const CUT_OFF_TIME = 24 * 60 * 60 * 1000; // 2 Hours in milliseconds.


exports.deleteOldMessages = functions.database.ref('/Message/{chatRoomId}').onWrite(async (change) => {
const ref = change.after.ref.parent; // reference to the parent
const now = Date.now();
const cutoff = now - CUT_OFF_TIME;
const oldItemsQuery = ref.orderByChild('seconds').endAt(cutoff);
const snapshot = await oldItemsQuery.once('value');
// create a map with all children that need to be removed
const updates = {};
snapshot.forEach(child => {
updates[child.key] = null;
});
// execute all updates in one go and return the result to end the function
return ref.update(updates);
});

And my database structure is: enter image description here


在评论中您表明您正在使用 Swift。从该图和屏幕截图中可以看出,您存储的时间戳以 1970 年以来的秒为单位,而 Cloud Functions 中的代码则假定它以毫秒为单位。

最简单的修复是:

// Cut off time. Child nodes older than this will be deleted.
const CUT_OFF_TIME = 24 * 60 * 60 * 1000; // 2 Hours in milliseconds.


exports.deleteOldMessages = functions.database.ref('/Message/{chatRoomId}').onWrite(async (change) => {
    const ref = change.after.ref.parent; // reference to the parent
    const now = Date.now();
    const cutoff = (now - CUT_OFF_TIME) / 1000; // convert to seconds
    const oldItemsQuery = ref.orderByChild('seconds').endAt(cutoff);
    const snapshot = await oldItemsQuery.once('value');
    // create a map with all children that need to be removed
    const updates = {};
    snapshot.forEach(child => {
        updates[child.key] = null;
    });
    // execute all updates in one go and return the result to end the function
    return ref.update(updates);
});

另请参阅我的回答:如何在 Firebase 云函数中传递特定日期后删除子节点? https://stackoverflow.com/questions/52600881/how-to-remove-a-child-node-after-a-certain-date-is-passed-in-firebase-cloud-func/52611778#52611778

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Firebase Cloud Functions 会在删除节点后立即删除节点,而不是 24 小时后 的相关文章

随机推荐