diff --git a/functions/index.js b/functions/index.js index 6c9922288ab5e2e94eb4f3e5a91f0ff6ca94e106..6fe86d6add8f3b6808baf4f381cf57491c2904d1 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); + }); + });