[PWA] 16. Clean IDB

IndexDB数据存储与清理
本文介绍了一种使用IndexDB存储数据的方法,并实现了一个只保留最新30条记录的功能。通过遍历数据索引并删除多余的旧记录来达到数据清理的目的。

When we save items to IndexDB, we need to think about clean the items or keep those in a short list.

 

IndexController.prototype._onSocketMessage = function(data) {
  var messages = JSON.parse(data);

  this._dbPromise.then(function(db) {
    if (!db) return;

    var tx = db.transaction('wittrs', 'readwrite');
    var store = tx.objectStore('wittrs');
    messages.forEach(function(message) {
      store.put(message);
    });

    // TODO: keep the newest 30 entries in 'wittrs',
    // but delete the rest.
    //
    // Hint: you can use .openCursor(null, 'prev') to
    // open a cursor that goes through an index/store
    // backwards.
    store.index('by-date').openCursor(null, 'prev')
        .then((cursor)=>{
          return cursor.advance(30); // only 30 itmes are kept
        }).then(function deleteCursor(cursor){
            if(!cursor){
              return;
            }else{
              cursor.delete();
              return cursor.continue().then(deleteCursor);
            }
        })
  });

  this._postsView.addPosts(messages);
};

 

转载于:https://www.cnblogs.com/Answer1215/p/5515785.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值