Skip to content

Instantly share code, notes, and snippets.

@Kyoss79
Last active April 1, 2019 09:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save Kyoss79/8cd37a54679804fdeb6d to your computer and use it in GitHub Desktop.
Save Kyoss79/8cd37a54679804fdeb6d 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.remove(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 * 60 * expires);
originalSet(key, {
data: val,
expire: expiryDate
});
} else {
originalSet(key, val);
}
};
return $delegate;
});
});
@simondevries
Copy link

Thanks for posting this! One thing I noticed is the $delegate 'rm' method has been renamed to 'remove' on line 31

@harisshahid
Copy link

In conversion it should be like this (1000 * 60 * 60 * expires). Otherwise it will convert it into minutes.
BTW it helps me a lot. Thanks

@Kyoss79
Copy link
Author

Kyoss79 commented Apr 1, 2019

Thanks for the feedback, will edit original post :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment