From 255e933379250234ef4c153d6654b83c37f968e5 Mon Sep 17 00:00:00 2001 From: Laurent Monin Date: Thu, 11 Jun 2015 14:25:58 +0200 Subject: [PATCH] mblinks: take care of removal of old cache versions --- lib/mblinks.js | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/lib/mblinks.js b/lib/mblinks.js index c8c1325..576b929 100644 --- a/lib/mblinks.js +++ b/lib/mblinks.js @@ -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);