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