import {Injectable} from '@angular/core'; import {ICache} from './cache.interface'; import {ISerializable} from './serializeable.interface'; @Injectable() export class LocalStorageCache implements ICache { private localStorage: any; constructor() { if (!localStorage) { throw new Error('Current browser does not support Local Storage'); } this.localStorage = localStorage; } get(key: string, type: {new(): ISerializable}): T { return this.restore(key, new type()); } restore(key: string, restoreInto: ISerializable): T { const result = this.localStorage.getItem(key); return result ? restoreInto.deserialize(result) : null; } set(key: string, data: ISerializable): string { this.localStorage.setItem(key, data.serialize()); return key; } keyExists(key: string) { return !!this.localStorage.getItem(key); } delete(key: string): boolean { const exists = this.keyExists(key); if (exists) { this.localStorage.removeItem(key); } return exists; } clear(): void { this.localStorage.clear(); } }