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

标签 html indexeddb

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

我想用当前日期时间和到期时间将值包装在一个对象中,当您获得该值时,检查时差,但这是最好的方法吗?

谢谢

最佳答案

是的,正如 Scott Marcus 和 dgrogan 所说的那样。另一个提示:如果您在时间戳上创建索引,则可以在“过期”值的范围内迭代游标,并在打开数据库后删除它们。

const open = indexedDB.open("demo");

open.onupgradeneeded = function () {
  const db = open.result;
  const store = db.createObjectStore("store");
  const index = store.createIndex("timestamp", "timestamp");

  // Populate with some dummy data, with about half from the past:
  for (let id = 0; id < 20; ++id) {
    store.put(
      {
        value: Math.random(),
        timestamp: new Date(Date.now() + (Math.random() - 0.5) * 10000),
      },
      id
    );
  }
};

open.onsuccess = function () {
  const db = open.result;
  const tx = db.transaction("store", "readwrite");
  // Anything in the past:
  const range = IDBKeyRange.upperBound(new Date());

  tx
    .objectStore("store")
    .index("timestamp")
    .openCursor(range).onsuccess = function (e) {
    const 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:
  const tx2 = db.transaction("store");
  tx2.objectStore("store").count().onsuccess = function (e) {
    console.log("records remaining: " + e.target.result);
  };
};

关于html - 如何将到期时间应用于 HTML5 indexeddb 中的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35511033/

相关文章:

javascript - 在 Dexie 数据库模式中指定不同的唯一键?

javascript - 有什么方法可以从 indexeddb 中检索随机行

javascript - 数组键路径上的索引找不到任何值

jquery - 在indexedDB中打开多个数据库连接是否不好?

javascript - 有什么方法可以将数据本地存储在 HTML5 应用程序中,并从任何已安装的浏览器访问它?

html - 如何使用css将hr隐藏在最后一里

html - 事件导航选项卡不应该有底线

html - 响应式 HTML 5 Canvas 与正文内容重叠

html - 在这种情况下垂直对齐的正确方法是什么?

jquery - 水平图像向上滑动