Last active
April 1, 2019 09:39
-
-
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.
This file contains 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
/** | |
* 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; | |
}); | |
}); |
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
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
Thanks for posting this! One thing I noticed is the $delegate 'rm' method has been renamed to 'remove' on line 31