Skip to content

Instantly share code, notes, and snippets.

@thomasbrueggemann
Last active August 29, 2015 14:17
Show Gist options
  • Save thomasbrueggemann/ec153a504658d8ac5808 to your computer and use it in GitHub Desktop.
Save thomasbrueggemann/ec153a504658d8ac5808 to your computer and use it in GitHub Desktop.
Objects in localStorage via setObject(k, v, ttl) / getObject(k,v) and optional TTL values
Storage.prototype.setObject = function(key, value, ttl) {
this.setItem(key, JSON.stringify(value));
if(ttl) {
this.setItem(key + "~ttl", moment.utc().add(ttl, "seconds").format("X"));
}
};
Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
// check ttl
var ttl = this.getItem(key + "~ttl");
if(ttl) {
var expired = moment(parseInt(ttl)).isAfter(moment.utc());
if(expired) {
this.removeItem(key);
this.removeItem(key + "~ttl");
return null;
}
}
return value && JSON.parse(value);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment