@apicart/js-utils
Version:
A small set of useful utilities for easier development
107 lines (86 loc) • 2.12 kB
text/typescript
import {
Json,
Console,
Objects
} from '.';
interface LocalStorageItemInterface {
expiration: number;
value: any;
}
class LocalStorage {
private _localStorageManager: Record<string, any> = {
_data: {},
getItem(key: string|number) {
return typeof this._data[key] === 'undefined' ? null : this._data[key];
},
setItem(key: string|number, value: string|number|null) {
this._data[key] = value;
},
removeItem(key: string|number) {
delete this._data[key];
},
clear() {
this._data = {};
},
key(key: number) {
return typeof Object.keys(this._data)[key] === 'undefined' ? null : Object.keys(this._data)[key];
}
};
constructor() {
if (typeof localStorage !== 'undefined') {
this._localStorageManager = localStorage;
}
}
public clear(): this
{
this._localStorageManager.clear();
return this;
}
public getItem(key: string): any | null
{
const itemString: string = this._localStorageManager.getItem(key);
let item: LocalStorageItemInterface | null = null;
if (itemString) {
item = Json.parse(itemString);
if (item.expiration !== null && item.expiration < this.getActualTimestamp()) {
item = null;
this.removeItem(key);
}
}
return item === null ? item : item.value;
}
public setItem(key: string, value: any, expiration: number | null = null): this
{
const item: LocalStorageItemInterface = {
expiration: expiration ? this.getActualTimestamp() + expiration : null,
value: value
};
try {
this._localStorageManager.setItem(key, Json.stringify(item));
} catch (error) {
Console.error(error);
}
return this;
}
public updateItem(key, value, expiration: number | null = null): this
{
const item = this.getItem(key) || {};
Objects.merge(item, value);
this.setItem(key, item, expiration);
return this;
}
public removeItem(key: string): this
{
this._localStorageManager.removeItem(key);
return this;
}
public hasItem(key: string): boolean
{
return this.getItem(key) !== null;
}
public getActualTimestamp(): number
{
return new Date().getTime();
}
}
export default new LocalStorage();