Last active
May 20, 2021 13:11
-
-
Save rafaeldcastro/76a1ac3919efb346fedf4b43f9b1b26a to your computer and use it in GitHub Desktop.
Angular LocalStorage Service
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
import { Injectable } from '@angular/core'; | |
import { APP_CONSTANTS } from '@constants/app.constants'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class LocalStorageService { | |
constructor() { } | |
static loadInitialState() { | |
return Object.keys(localStorage).reduce((state: any, storageKey) => { | |
if (storageKey.includes(`_cap_${APP_CONSTANTS.APP_PREFIX}`)) { | |
const stateKeys = storageKey | |
.replace(`_cap_${APP_CONSTANTS.APP_PREFIX}`, '') | |
.toLowerCase() | |
.split('.') | |
.map(key => | |
key | |
.split('-') | |
.map((token, index) => | |
index === 0 | |
? token | |
: token.charAt(0).toUpperCase() + token.slice(1) | |
) | |
.join('') | |
); | |
let currentStateRef = state; | |
stateKeys.forEach((key, index) => { | |
if (index === stateKeys.length - 1) { | |
currentStateRef[key] = JSON.parse(localStorage.getItem(storageKey)); | |
return; | |
} | |
currentStateRef[key] = currentStateRef[key] || {}; | |
currentStateRef = currentStateRef[key]; | |
}); | |
} | |
return state; | |
}, {}); | |
} | |
static setItem(key: string, value: any) { | |
localStorage.setItem(`_cap_${APP_CONSTANTS.APP_PREFIX}-${key}`, JSON.stringify(value)); | |
} | |
static getItem(key: string) { | |
return JSON.parse(localStorage.getItem(`_cap_${APP_CONSTANTS.APP_PREFIX}-${key}`)); | |
} | |
static removeItem(key: string) { | |
localStorage.removeItem(`_cap_${APP_CONSTANTS.APP_PREFIX}-${key}`); | |
} | |
/** Tests that localStorage exists, can be written to, and read from. */ | |
static testLocalStorage() { | |
const testValue = 'testValue'; | |
const testKey = 'testKey'; | |
let retrievedValue: string; | |
const errorMessage = 'localStorage did not return expected value'; | |
this.setItem(testKey, testValue); | |
retrievedValue = this.getItem(testKey); | |
this.removeItem(testKey); | |
if (retrievedValue !== testValue) { | |
throw new Error(errorMessage); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment