restore: Implement cleanup for expired blobs.

This commit is contained in:
Renée Kooi 2017-09-28 12:28:57 +02:00
parent e93fe3ca80
commit a542fdf42d
No known key found for this signature in database
GPG key ID: 30516CF2A8E63718

View file

@ -1,3 +1,4 @@
const prettyBytes = require('prettier-bytes')
const indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB
const isSupported = !!indexedDB
@ -175,6 +176,38 @@ class IndexedDBStore {
return waitForRequest(request)
})
}
/**
* Delete all stored blobs that have an expiry date that is before Date.now().
* This is a static method because it deletes expired blobs from _all_ Uppy instances.
*/
static cleanup () {
return connect(DB_NAME).then((db) => {
const transaction = db.transaction([STORE_NAME], 'readwrite')
const store = transaction.objectStore(STORE_NAME)
const request = store.index('expires')
.openCursor(IDBKeyRange.upperBound(Date.now()))
return new Promise((resolve, reject) => {
request.onsuccess = (event) => {
const cursor = event.target.result
if (cursor) {
const entry = cursor.value
console.log(
'[IndexedDBStore] Deleting record', entry.fileID,
'of size', prettyBytes(entry.data.size),
'- expired on', new Date(entry.expires))
cursor.delete() // Ignoring return value … it's not terrible if this goes wrong.
cursor.continue()
} else {
resolve()
}
}
request.onerror = reject
})
}).then((db) => {
db.close()
})
}
}
IndexedDBStore.isSupported = isSupported