Created
July 12, 2017 12:56
-
-
Save jordan112/a9d62e1c83fd39e333ac545e0a4f53e1 to your computer and use it in GitHub Desktop.
ClientDataService to abstract away local, session or cookie fallback
This file contains hidden or 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 { CookieService } from 'ngx-cookie'; | |
declare let Modernizr: any; | |
@Injectable() | |
export class ClientDataService { | |
private KEY_PREFIX = 'prodreg'; | |
private KEY_SEPARATOR = '|'; | |
private storage = null; | |
constructor(private cookieService: CookieService) { | |
this.storage = this.getStorage(); | |
} | |
private getKey(key: string) { | |
return this.KEY_PREFIX + this.KEY_SEPARATOR + key; | |
} | |
private set(key: string, value: any) { | |
this.storage ? this.storage.setItem(this.getKey(key), value) : this.cookieService.put(this.getKey(key), value); | |
} | |
private get(key: string) { | |
return (this.storage ? this.storage.getItem(this.getKey(key)) : this.cookieService.get(this.getKey(key))); | |
} | |
private remove(key: string) { | |
this.storage ? this.storage.removeItem(this.getKey(key)) : this.cookieService.remove(this.getKey(key)); | |
} | |
private clear() { | |
this.storage ? this.storage.clear() : this.cookieService.removeAll(); | |
} | |
/// this will fallback down from local, to session to cookies | |
private getStorage() { | |
if (Modernizr.localstorage) { | |
return localStorage; | |
} else if (Modernizr.sessionstorage) { | |
return sessionStorage; | |
} else { | |
return null; | |
} | |
} | |
public setItem(key: string, value: any) { | |
this.set(key, value); | |
} | |
public getItem(key: string) { | |
return this.get(key); | |
} | |
public removeItem(key: string) { | |
this.remove(key); | |
} | |
public clearAllItems() { | |
return this.clear(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment