如何将到期时间应用于HTML5 indexeddb中的键?

ome*_*ega 3 html5 indexeddb

在html5 api中的indexedDB中,我可以使用它来存储键值对.但是,如何确保在添加某个键值后1天后,该键应自动从数据库中删除.

我正在考虑将值包装在具有当前日期时间和到期时间的对象中,当您获取该值时,请检查时差,但这是最好的方法吗?

谢谢

Jos*_*ell 9

是的,Scott Marcus和dgrogan说的是什么.还有一个提示:如果在时间戳上创建索引,则可以在"过期"值范围内迭代游标,并在打开数据库后删除它们.

var open = indexedDB.open('demo');
open.onupgradeneeded = function() {
  var db = open.result;
  var store = db.createObjectStore('store');
  var index = store.createIndex('timestamp', 'timestamp');

  // Populate with some dummy data, with about half from the past:
  for (var id = 0; id < 20; ++id) {
    store.put({
      value: Math.random(),
      timestamp: new Date(Date.now() + (Math.random()-0.5) * 10000)
    }, id);
  }
};
open.onsuccess = function() {
  var db = open.result;
  var tx = db.transaction('store', 'readwrite');

  // Anything in the past:
  var range = IDBKeyRange.upperBound(new Date());

  tx.objectStore('store').index('timestamp').openCursor(range)
    .onsuccess = function(e) {
      var cursor = e.target.result;
      if (!cursor) return;
      console.log('deleting: ' + cursor.key);
      cursor.delete();
      cursor.continue();
    };

  // This transaction will run after the first commits since
  // it has overlapping scope:
  var tx2 = db.transaction('store');
  tx2.objectStore('store').count().onsuccess = function(e) {
    console.log('records remaining: ' + e.target.result);
  };
};
Run Code Online (Sandbox Code Playgroud)


dgr*_*gan 5

正在考虑支持自动过期 IndexedDB 和其他存储数据。请参阅https://github.com/whatwg/storage/issues/11。如果您能在那里描述您的用例,那将会很有帮助。

与此同时,你必须做一些你概述的或斯科特马库斯建议的事情。


Sco*_*cus 3

IndexedDB只能通过代码修改。它没有自动功能。为什么不直接使用时间戳值存储数据并修改代码以在时间戳过期时将其删除?

  • 我不同意。我们为人类开发软件,并且应该以对人类的同理心来编写软件。因此,软件开发人员有责任不要将垃圾留在人们的计算机上,从而给他们带来麻烦。我的孩子不知道如何清除缓存,我的父母也不知道。另外,我怀疑清除缓存是否会有帮助,因为这可能被认为是 cookie 数据。如果他们清除 cookie,他们将失去每个站点的登录会话并导致头痛。_cache_ 不需要手动清除,因为它应该有大小限制并自动驱逐未使用的内容。 (6认同)
  • 作为用户,我关心。我不希望我一年前访问过的网站在我的电脑上保存几兆字节的数据。 (4认同)