Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expiring URLs with Firebase

Tags:

firebase

How does someone create temporary URLs that point to Firebase data, but the data (and URLs) will be destroyed after a specific time, i.e., 5 minutes or 15 minutes?

like image 438
nodebase Avatar asked Dec 24 '12 00:12

nodebase


1 Answers

Depending on exactly how the data is being stored, there are a few different options for removing the data by timestamp.

Assuming the data is unsorted, and you have stored the timestamp as a field in each record, then you may simply begin reading from the first record and deleting them until you find one you want to keep:

<script>
var FB = new Firebase(YOUR_URL);
var childRef = FB.child( TABLE_WITH_RECORDS_TO_DELETE );
var oneWeekAgo = new Date().getTime()-1000*60*60*24*7; // one week ago

var fx = function(snapshot) { // keep a ref to this so we can call off later
   var v = snapshot.val();
   if( v.expires_on_date < oneWeekAgo ) {
      // delete the record
      snapshot.ref().remove();
   }
   else {
      // we found the first keeper, so we are done
      childRef.off('child_added', fx);
   }
}

// fetched records and test to see how old they are
childRef.on('childAdded', fx);
</script>

If the data is sorted by timestamp, you can retrieve and delete them as follows:

var FB = new Firebase(YOUR_URL);
var childRef = FB.child( TABLE_WITH_RECORDS_TO_DELETE );
var oneWeekAgoMinusOne = new Date().getTime()-1000*60*60*24*7-1; // one week ago

// fetched using endAt, so only retrieving older than 1 week
childRef.endAt( oneWeekAgoMinusOne ).on('childAdded', function(snapshot) {
    // delete the record
   snapshot.ref().remove();
});
like image 197
Kato Avatar answered Oct 06 '22 00:10

Kato