使用Firebase使URL失效

时间:2012-12-24 00:18:43

标签: firebase

有人如何创建指向Firebase数据的临时URL,但数据(和URL)将在特定时间(即5分钟或15分钟)后销毁?

1 个答案:

答案 0 :(得分:5)

根据数据的确切存储方式,有一些不同的选项可以按时间戳删除数据。

假设数据未排序,并且您已将时间戳存储为每个记录中的字段,那么您可能只是从第一个记录开始读取并删除它们,直到找到要保留的记录:

<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>

如果数据按时间戳排序,您可以按如下方式检索和删除它们:

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();
});