Skip to content

Instantly share code, notes, and snippets.

@sgromkov
Created August 25, 2020 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgromkov/8d1c7985f9b3caf54d50753ac0ff713d to your computer and use it in GitHub Desktop.
Save sgromkov/8d1c7985f9b3caf54d50753ac0ff713d to your computer and use it in GitHub Desktop.
LocalStorage wrapper with expired time for keys
import { isValidJsonObject } from 'https://gist.github.com/sgromkov/bd65afb17cb26f70def920a33ace2ada#file-jsonvalidator-js';
/**
* Wrapper above the Storage object
* which can be used to access the current origin's local storage space.
*
* It provides all the methods and properties of localStorage,
* but extends them by adding expiration date for keys.
*
* Use it instead of Cookie if you need to save a value that should be destroyed
* when it's life time expires, and if you don't need to send this value to server.
*
* It helps you avoid clogging up Cookie storage and keep request headers cleaner.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Storage
*
*/
const localStorager = {
/**
* When passed a number `n`, this method will return the name of the nth key in the storage.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Storage/key
* @param {*} keyNumber
* An integer representing the number of the key you want to get the name of.
* This is a zero-based index.
* @return { String }
* A DOMString containing the name of the key. If the index does not exist, null is returned.
*/
key: function(keyNumber) {
return localStorage.key(keyNumber);
},
/**
* When passed a key name, will return that key's value,
* if the expiration date exists and not expired.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem
* @param { String } keyName
* A DOMString containing the name of the key you want to retrieve the value of.
* @return { String }
* A DOMString containing the value of the key.
* If the key does not exist, or it's life time has expired, null is returned.
*/
getItem: function(keyName) {
const storageItem = localStorage.getItem(keyName);
if (storageItem === null) {
return null;
}
if (!isValidJsonObject(storageItem)) {
return storageItem;
}
const data = JSON.parse(storageItem);
if (!data.hasOwnProperty('value') || !data.hasOwnProperty('expired')) {
return storageItem;
}
const currentTimestamp = Date.now();
const expirationTimestamp = data.expired;
const storageItemIsAlive = (
expirationTimestamp === null
|| currentTimestamp < parseInt(expirationTimestamp)
);
if (storageItemIsAlive) {
return data.value;
} else {
localStorage.removeItem(keyName);
return null;
}
},
/**
* When passed a key name and value, will add that key to the storage,
* or update that key's value if it already exists.
*
* Extension: When passed an end time of the value's lifetime will save it in a Storage value.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem
* @param { String } keyName
* A DOMString containing the name of the key you want to create/update.
* @param { String } keyValue
* A DOMString containing the value you want to give the key you are creating/updating.
* @param { String|Number|Null } expiresAtTimestamp
* A timestamp when the value should be destroyed.
* If `null` value will not be destroyed.
* @return { undefined }
*/
setItem: function(keyName, keyValue, expiresAtTimestamp = null) {
const data = {
value: keyValue,
expired: expiresAtTimestamp
};
return localStorage.setItem(
keyName,
JSON.stringify(data)
);
},
/**
* When passed a key name, will remove that key from the storage.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Storage/removeItem
* @param { String } keyName
* A DOMString containing the name of the key you want to remove.
* @return { undefined }
*/
removeItem: function(keyName) {
return localStorage.removeItem(keyName);
},
/**
* When invoked, will empty all keys out of the storage.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Storage/clear
* @return { undefined }
*/
clear: function() {
return localStorage.clear();
},
/**
* Returns an integer representing the number of data items stored in the Storage object.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Storage/length
* @readonly
* @return { Number }
* The number of items stored in the Storage object.
*/
get length() {
return localStorage.length;
}
};
export default localStorager;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment