Last active
August 29, 2015 14:17
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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