From 242cd2bca93dd9ec8a04a89c39e051e037d3b0e9 Mon Sep 17 00:00:00 2001 From: Marco Endrizzi <me00531@surrey.ac.uk> Date: Sun, 25 Apr 2021 17:06:52 -0700 Subject: [PATCH] Added cloud functions to remove old signals/events --- functions/index.js | 46 ++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/functions/index.js b/functions/index.js index 6c99222..6fe86d6 100644 --- a/functions/index.js +++ b/functions/index.js @@ -1,9 +1,39 @@ -// const functions = require("firebase-functions"); +const functions = require("firebase-functions"); +const admin = require("firebase-admin"); +admin.initializeApp(functions.config().firebase); -// // Create and Deploy Your First Cloud Functions -// // https://firebase.google.com/docs/functions/write-firebase-functions -// -// exports.helloWorld = functions.https.onRequest((request, response) => { -// functions.logger.info("Hello logs!", {structuredData: true}); -// response.send("Hello from Firebase!"); -// }); +/* Delete signals older than 15m */ +exports.deleteOldSignals = functions.pubsub + .schedule("* * * * *").onRun(() => { + const ref = admin.database().ref("signals"); // reference to the items + const now = Date.now(); + const cutoff = now - 2 * 60 * 1000; // 2m + const oldItemsQuery = ref.orderByChild("timestamp").endAt(cutoff); + return oldItemsQuery.once("value", function(snapshot) { + // create a map with all children that need to be removed + const updates = {}; + snapshot.forEach(function(child) { + updates[child.key] = null; + }); + // execute all updates in one go and return the result + return ref.update(updates); + }); + }); + +/* Delete events older than 5 hours */ +exports.deleteOldEvents = functions.pubsub + .schedule("0 * * * *").onRun(() => { + const ref = admin.database().ref("events"); // reference to the items + const now = Date.now(); + const cutoff = now - 5 * 60 * 60 * 1000; + const oldItemsQuery = ref.orderByChild("timestamp").endAt(cutoff); + return oldItemsQuery.once("value", function(snapshot) { + // create a map with all children that need to be removed + const updates = {}; + snapshot.forEach(function(child) { + updates[child.key] = null; + }); + // execute all updates in one go and return the result + return ref.update(updates); + }); + }); -- GitLab