Expiring URLs with Firebase

后端 未结 1 1289
挽巷
挽巷 2021-02-10 16:55

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?

相关标签:
1条回答
  • 2021-02-10 17:50

    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();
    });
    
    0 讨论(0)
提交回复
热议问题