35 lines
958 B
TypeScript
35 lines
958 B
TypeScript
const _store = window.localStorage
|
|
const Storage = {
|
|
put(key: string, value: any, expire = -1) {
|
|
expire = expire == -1 ? -1 : Date.now() + expire * 1000;
|
|
_store.setItem(key, JSON.stringify({
|
|
value,
|
|
expire
|
|
}))
|
|
},
|
|
get<T>(key: string, defaultValue: null | T = null) {
|
|
const data = _store.getItem(key);
|
|
if (data == null) {
|
|
return data;
|
|
}
|
|
try {
|
|
const _data = JSON.parse(data);
|
|
if (_data.expire) {
|
|
if (_data.expire != -1 && _data.expire < Date.now()) {
|
|
Storage.remove(key);
|
|
return defaultValue;
|
|
}
|
|
return _data.value as T;
|
|
}
|
|
return _data as T;
|
|
} catch (_) {
|
|
console.log(_)
|
|
}
|
|
return data as T;
|
|
},
|
|
remove(key: string) {
|
|
_store.removeItem(key);
|
|
}
|
|
}
|
|
export default Storage
|