Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Hank-wood/b52ef10ee7c7aaba3c7fd6936179ddd0 to your computer and use it in GitHub Desktop.
Save Hank-wood/b52ef10ee7c7aaba3c7fd6936179ddd0 to your computer and use it in GitHub Desktop.
Extend the localStorageService for Angular (https://github.com/grevory/angular-local-storage) with the possibility of expiring entries.
/**
* extend the localStorageService (https://github.com/grevory/angular-local-storage)
*
* - now its possible that data stored in localStorage can expire and will be deleted automagically
* - usage localStorageService.set(key, val, expire)
* - expire is an integer defininig after how many hours the value expires
* - when it expires, it is deleted from the localStorage
*/
app.config(($provide) => {
$provide.decorator('localStorageService', ($delegate) => {
//store original get & set methods
var originalGet = $delegate.get,
originalSet = $delegate.set;
/**
* extending the localStorageService get method
*
* @param key
* @returns {*}
*/
$delegate.get = (key) => {
if(originalGet(key)) {
var data = originalGet(key);
if(data.expire) {
var now = Date.now();
// delete the key if it timed out
if(data.expire < now) {
$delegate.rm(key);
return null;
}
return data.data;
} else {
return data;
}
} else {
return null;
}
};
/**
* set
* @param key key
* @param val value to be stored
* @param {int} expires hours until the localStorage expires
*/
$delegate.set = (key, val, expires) => {
var expiryDate = null;
if(angular.isNumber(expires)) {
expiryDate = Date.now() + (1000 * 60 * expires);
originalSet(key, {
data: val,
expire: expiryDate
});
} else {
originalSet(key, val);
}
};
return $delegate;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment