UNPKG

@xompass/sdk-cloud-api

Version:

Xompass Client for cloud-api

61 lines (55 loc) 1.54 kB
import logger from '../services/core/XompassLogger'; import { ClientStorage } from './ClientStorage'; export class BrowserStorage implements ClientStorage { /** * @method get * @param key Storage key name * @description * The getter will return any type of data persisted in localStorage. */ get(key: string): any { const data = BrowserStorage.parse(localStorage.getItem(key)); if (!data || data.e && new Date(data.e) < new Date()) { return null; } return data.v; } /** * @method set * @param key Storage key name * @param value Any value * @param [expires] The date of expiration (Optional) * @description * The setter will return any type of data persisted in localStorage. */ set(key: string, value: any, expires?: Date): void { const data = { v: value, e: expires ? expires.getTime() : undefined }; localStorage.setItem(key, JSON.stringify(data)); } /** * @method remove * @param key Storage key name * @description * This method will remove a localStorage item from the client. */ remove(key: string): void { localStorage.removeItem(key); } /** * @method parse * @param value Input data expected to be JSON * @description * This method will parse the string as JSON if possible, otherwise will * return the value itself. */ private static parse(value: string | null): any { if (!value) { return value; } try { return JSON.parse(value); } catch (e) { return value; } } }