Is there a simple way to locally store a JSON value with a TTL in a Firefox SDK add-on?
As far as I can tell, Firefox forces you to use their 'simple-storage'
library. I can't use a third-party library such as jStorage.
No, simple-storage
and DOM Storage are completely different things meaning that you cannot use a library like jStorage which is meant for work with DOM Storage.
Then again, storing JSON and implementing TTL is simple enough to implement yourself. For JSON you use JSON.parse
and JSON.stringify
. For TTL you simply store the TTL values somewhere and look them up when necessary. Something like this:
var AdvancedStorage = {
_storage: require("simple-storage").storage,
// Keep TTL data in a special storage field
_ttlData: null,
_readTTLData() {
if (this._storage._ttl)
this._ttlData = JSON.parse(this._storage._ttl);
else
this._ttlData = {};
},
_saveTTLData() {
this._storage._ttl = JSON.stringify(this._ttlData);
},
// Special data manipulation functions
set: function(key, value, options) {
this._storage[key] = JSON.stringify(value);
this.setTTL(key, options && "TTL" in options ? options.TTL : 0);
},
get: function(key, default) {
if (!this._storage.hasOwnProperty(key))
return default;
// Check whether setting has expired
if (!this._ttlData)
this._readTTLData();
if (this._ttlData.hasOwnProperty(key) && this._ttlData[key] <= Date.now())
return default;
return JSON.parse(this._storage[key]);
},
deleteKey: function(key) {
delete this._storage[key];
},
// Setting the TTL value
setTTL(key, ttl) {
if (!this._ttlData)
this._readTTLData();
if (ttl > 0)
this._ttlData[key] = Date.now() + ttl;
else
delete this._ttlData[key];
this._saveTTLData();
}
};
I didn't test this code but this should be pretty much all the code you need to implement this kind of feature.