Облачные функции Firebase удаляют узлы сразу после, а не через 24 часа - PullRequest
2 голосов
/ 27 мая 2019

Моя цель - удалить все узлы сообщений через 24 часа после их отправки с использованием облачных функций Firebase и базы данных реального времени. Я попытался скопировать и вставить ответ из этого поста , однако по какой-то причине сообщения удаляются непосредственно после их создания, а не через 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);
});

И моя структура базы данных: enter image description here

1 Ответ

1 голос
/ 02 июня 2019

В комментариях вы указали, что используете Swift.Из этого и снимка экрана видно, что вы храните метку времени в секундах с 1970 года, а код в облачных функциях предполагает, что она указана в миллисекундах.

Самое простое исправление:

// 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?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...