Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Wrapper to add functionality to Web Storage API
- */
- class Storage {
- // We can use localStorage or sessionStorage with the same API
- constructor(name = "localStorage") {
- this.store = window[name];
- // Constant name of the entity array where we store all entity keys
- this.KEY_LIST_NAME = "KEYS";
- }
- // Save on storage the item with the setItem API
- _saveItem(key, data) {
- const transformed = JSON.stringify(data);
- this.store.setItem(key, transformed);
- }
- // Add key to the entity KEYS
- _addKeyToList(key) {
- const keyList = this.get(this.KEY_LIST_NAME) || [];
- if (keyList.includes(key)) {
- return;
- }
- this._saveItem(this.KEY_LIST_NAME, [...keyList, key]);
- }
- // Remove key from the entity KEY_LIST_NAME
- _removeKeyToList(keyToRemove) {
- const keyList = this.get(this.KEY_LIST_NAME);
- const newList = keyList.filter(key => key !== keyToRemove);
- this._saveItem(this.KEY_LIST_NAME, newList);
- }
- // Set data into entity with name key
- set(key, data) {
- this._saveItem(key, data);
- this._addKeyToList(key);
- }
- // Get data from entity with name key
- get(key) {
- const data = this.store.getItem(key);
- return data ? JSON.parse(data) : undefined;
- }
- // Remove entire entity from the store with name key
- remove(key) {
- this.store.removeItem(key);
- this._removeKeyToList(key);
- }
- // Return the list of keys present in the store
- list() {
- return this.get(this.KEY_LIST_NAME);
- }
- // Clean all the storage
- clear() {
- this.list().forEach(key => {
- if (this.exist(key)) {
- return this.remove(key);
- }
- return this._removeKeyToList(key);
- });
- }
- // Return boolean if exist the key in the storage
- exist(key) {
- const keyList = this.get(this.KEY_LIST_NAME);
- return keyList.includes(key);
- }
- }
Add Comment
Please, Sign In to add comment