在html5 api中的indexedDB中,我可以使用它来存储键值对.但是,如何确保在添加某个键值后1天后,该键应自动从数据库中删除.
我正在考虑将值包装在具有当前日期时间和到期时间的对象中,当您获取该值时,请检查时差,但这是最好的方法吗?
谢谢
是的,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)
正在考虑支持自动过期 IndexedDB 和其他存储数据。请参阅https://github.com/whatwg/storage/issues/11。如果您能在那里描述您的用例,那将会很有帮助。
与此同时,你必须做一些你概述的或斯科特马库斯建议的事情。
IndexedDB只能通过代码修改。它没有自动功能。为什么不直接使用时间戳值存储数据并修改代码以在时间戳过期时将其删除?
| 归档时间: |
|
| 查看次数: |
3462 次 |
| 最近记录: |