Delete firebase data older than 2 hours

后端 未结 5 775
太阳男子
太阳男子 2020-11-22 03:17

I would like to delete data that is older than two hours. Currently, on the client-side, I loop through all the data and run a delete on the outdated data. When I do this, t

5条回答
  •  悲&欢浪女
    2020-11-22 03:54

    I have a http triggered cloud function that deletes nodes, depending on when they were created and their expiration date.

    When I add a node to the database, it needs two fields: timestamp to know when it was created, and duration to know when the offer must expire.

    Then, I have this http triggered cloud function:

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp();
    
    /**
     * @function HTTP trigger that, when triggered by a request, checks every message of the database to delete the expired ones.
     * @type {HttpsFunction}
     */
    exports.removeOldMessages = functions.https.onRequest((req, res) => {
        const timeNow = Date.now();
        const messagesRef = admin.database().ref('/messages');
        messagesRef.once('value', (snapshot) => {
            snapshot.forEach((child) => {
                if ((Number(child.val()['timestamp']) + Number(child.val()['duration'])) <= timeNow) {
                    child.ref.set(null);
                }
            });
        });
        return res.status(200).end();
    });
    

    You can create a cron job that every X minutes makes a request to the URL of that function: https://cron-job.org/en/

    But I prefer to run my own script, that makes a request every 10 seconds:

    watch -n10 curl -X GET https://(your-zone)-(your-project-id).cloudfunctions.net/removeOldMessages
    

提交回复
热议问题