1

So i have a database structure where i save an event with a timestamp value that dictates when the event will expire and be removed

so i created a firebase cloud function where i compare the time now (Date().now) with the timestamp in the database

the problem is when the code gets run the event gets removed immediately

here is the code:

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });

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

exports.removeOldMessages = functions.https.onRequest((req, res) => {
    const messagesRef = admin.database().ref('events')
    messagesRef.once('value', (snapshot) => {
        snapshot.forEach((child) => {
            child.forEach((child) => {
                if (Number(child.val()['endDate']) >= new Date().getTime()) {
                   child.ref.set(null)
              }
            })
        })
    })
    return res.status(200).end()
})
{   "events" : {
"N5iTuYzAbJa02RauxCl3uh2Nggz1" : {
  "-LNmIvSdrwK96KCGcmXm" : {
    "addedBy" : "Riyadh Figures",
    "coordinate" : [ 24.70914690943994, 46.78851541131735 ],
    "endDate" : "1538442801.0",
    "imagePath" : "-LNmIvSdrwK96KCGcmXm",
    "key" : "-LNmIvSdrwK96KCGcmXm",
    "title" : "hjihgf",
    "userPicture" : "N5iTuYzAbJa02RauxCl3uh2Nggz1"
  }
}   },   "user_profiles" : {
"N5iTuYzAbJa02RauxCl3uh2Nggz1" : {
  "email" : "riyadhfigures.official@gmail.com",
  "name" : "Riyadh Figures",
  "profile_picture" : "https://lh6.googleusercontent.com/-HfLRYyyTAxQ/AAAAAAAAAAI/AAAAAAAAAAA/AAN31DVNc5koC_GGuww6hxcMKPkx4niY-A/s96-c/photo.jpg"
},
"ah00Fe5hHnQM8tyceLE1xpWznUw1" : {
  "email" : "lenepouv@gmail.com",
  "name" : "Mbm Al Osaimi",
  "profile_picture" : "https://lh6.googleusercontent.com/-M0JCv0lMNTE/AAAAAAAAAAI/AAAAAAAAAIU/0M2Cef0YLOU/s96-c/photo.jpg"
},
"m1zj6gDEoUa9aCdPcazrb0rTuFj2" : {
  "email" : "mb.osaimi@gmail.com",
  "name" : "Mosab Al Osaimi",
  "profile_picture" : "https://lh5.googleusercontent.com/-X5va1C-uNpU/AAAAAAAAAAI/AAAAAAAAAAc/GVSZLwv46U0/s96-c/photo.jpg"
}   } }
mbm
  • 57
  • 6
  • It's impossible to say why this doesn't work without seeing a sample of the JSON you're trying to parse (as text, no screenshots please). You can get this by clicking the "Export JSON" link in your [Firebase Database console](https://console.firebase.google.com/project/_/database/data). But for a well tested, working example of deleting older nodes, see https://stackoverflow.com/a/32012520, https://github.com/firebase/functions-samples/tree/master/delete-old-child-nodes and https://stackoverflow.com/a/37504961. – Frank van Puffelen Oct 02 '18 at 03:03
  • @FrankvanPuffelen i updated the post with the JSON, the "endDate" node is where the timestamp is located – mbm Oct 02 '18 at 13:13
  • @FrankvanPuffelen I compare the end date timestamp with the current time like this "if (Number(child.val()['endDate']) <= timeNow { child.ref.set(null) }" – mbm Oct 02 '18 at 13:17
  • @FrankvanPuffelen sorry for asking too many questions. Does the timestamp in "endDate" look correct? because the timestamp gets pushed to firebase from a date picker in swift with no seconds in the date picker i just grab the timestamp from the date picker after the user selects a date/time and presses submit. i'm not sure if the problem is with the timestamp or something else. – mbm Oct 02 '18 at 13:22
  • You're storing the `endDate` timestamp as a string, which is an anti-pattern. I'm not sure if that's the cause of this problem though, as the comparison looks ok. You might want to `console.log(Number(child.val()['endDate'])+", "+new Date().getTime())` to see the values that you're comparing. – Frank van Puffelen Oct 02 '18 at 13:51
  • @FrankvanPuffelen okay i consoled logged it. here it is: 1538442801, 1538493156083 – mbm Oct 02 '18 at 15:14
  • @FrankvanPuffelen the current time timestamp is longer than the timestamp saved from swift. why is that? – mbm Oct 02 '18 at 15:16
  • @FrankvanPuffelen btw the endDate timestamp was grabbed from datePicker.date.timeIntervalSince1970 in Swift – mbm Oct 02 '18 at 15:20

1 Answers1

0

Swift uses intervals/timestamps in seconds with the fractional part indicating the subsecond details. Most other platforms use milliseconds. That means that there is a 1000x difference between the values, which explains why your comparison doesn't work.

The simplest fix is to multiple or divide by 1000. E.g.

if (1000*Number(child.val()['endDate']) >= new Date().getTime()) {
   child.ref.set(null)
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • THANK YOU SOOOOOOOOO MUCH!!!!!! I SPEND A DAY AND A HALF TRYING TO FIX THIS. THANK YOU. – mbm Oct 02 '18 at 15:44