mblinks: take care of removal of old cache versions

This commit is contained in:
Laurent Monin 2015-06-11 14:25:58 +02:00
parent 0b49e16cae
commit 255e933379

View file

@ -13,9 +13,9 @@
// mblinks.searchAndDisplayMbLink(album_link, 'release', function (link) { $('div#there').after(link); } );
// }
// cachekey = textual key used to store cached data in local storage
// user_cache_key = textual key used to store cached data in local storage
// expiration = time in minutes before an entry is refreshed, value <= 0 disables cache reads
var MBLinks = function (cachekey, expiration) {
var MBLinks = function (user_cache_key, expiration) {
this.supports_local_storage = function () {
try {
return !!localStorage.getItem;
@ -58,7 +58,8 @@ var MBLinks = function (cachekey, expiration) {
this.cache = {};
this.expirationMinutes = parseInt(expiration, 10);
var cache_version = 2;
this.cache_key = cachekey + '-v' + cache_version;
this.user_cache_key = user_cache_key;
this.cache_key = this.user_cache_key + '-v' + cache_version;
this.mb_server = '//musicbrainz.org';
// overrides link title and img src url (per type), see createMusicBrainzLink()
this.type_link_info = {
@ -85,6 +86,8 @@ var MBLinks = function (cachekey, expiration) {
this.cache = JSON.parse(localStorage.getItem(this.cache_key) || '{}');
// remove old entries
this.clearCacheExpired();
// remove old cache versions
this.removeOldCacheVersions();
};
this.saveCache = function () {
@ -96,6 +99,22 @@ var MBLinks = function (cachekey, expiration) {
}
};
this.removeOldCacheVersions = function () {
var to_remove = [];
for (var i = 0, len = localStorage.length; i < len; ++i) {
var key = localStorage.key(i);
if (key.indexOf(this.user_cache_key) === 0) {
if (key != this.cache_key) { // we don't want to remove current cache
to_remove.push(key);
}
}
}
// remove old cache keys
for (var i = 0; i < to_remove.length; i++) {
localStorage.removeItem(to_remove[i]);
}
};
this.clearCacheExpired = function() {
//var old_cache_entries = Object.keys(this.cache).length;
//console.log("clearCacheExpired " + old_cache_entries);