philomena/assets/js/utils/store.ts

66 lines
1.6 KiB
TypeScript
Raw Normal View History

2019-10-05 02:09:52 +02:00
/**
* localStorage utils
*/
export const lastUpdatedSuffix = '__lastUpdated';
2019-10-05 02:09:52 +02:00
export default {
2022-03-26 00:28:45 +01:00
set(key: string, value: unknown) {
2019-10-05 02:09:52 +02:00
try {
localStorage.setItem(key, JSON.stringify(value));
return true;
}
2024-06-12 22:56:58 +02:00
catch {
2019-10-05 02:09:52 +02:00
return false;
}
},
2022-03-26 00:28:45 +01:00
get<Value = unknown>(key: string): Value | null {
2019-10-05 02:09:52 +02:00
const value = localStorage.getItem(key);
2022-03-26 00:28:45 +01:00
if (value === null) return null;
2019-10-05 02:09:52 +02:00
try {
return JSON.parse(value);
}
2024-06-12 22:56:58 +02:00
catch {
2022-03-26 00:28:45 +01:00
return value as unknown as Value;
2019-10-05 02:09:52 +02:00
}
},
2022-03-26 00:28:45 +01:00
remove(key: string) {
2019-10-05 02:09:52 +02:00
try {
localStorage.removeItem(key);
return true;
}
2024-06-12 22:56:58 +02:00
catch {
2019-10-05 02:09:52 +02:00
return false;
}
},
// Watch changes to a specified key - returns value on change
2022-03-26 00:28:45 +01:00
watch(key: string, callback: (value: unknown) => void) {
const handler = (event: StorageEvent) => {
2019-10-05 02:09:52 +02:00
if (event.key === key) callback(this.get(key));
};
window.addEventListener('storage', handler);
return () => window.removeEventListener('storage', handler);
2019-10-05 02:09:52 +02:00
},
// set() with an additional key containing the current time + expiration time
2022-03-26 00:28:45 +01:00
setWithExpireTime(key: string, value: unknown, maxAge: number) {
2019-10-05 02:09:52 +02:00
const lastUpdatedKey = key + lastUpdatedSuffix;
const lastUpdatedTime = Date.now() + maxAge;
2024-06-12 22:56:58 +02:00
return this.set(key, value) && this.set(lastUpdatedKey, lastUpdatedTime);
2019-10-05 02:09:52 +02:00
},
// Whether the value of a key set with setWithExpireTime() has expired
2022-03-26 00:28:45 +01:00
hasExpired(key: string) {
2019-10-05 02:09:52 +02:00
const lastUpdatedKey = key + lastUpdatedSuffix;
2022-03-26 00:28:45 +01:00
const lastUpdatedTime = this.get<number>(lastUpdatedKey);
2019-10-05 02:09:52 +02:00
2022-03-26 00:44:28 +01:00
return lastUpdatedTime === null || Date.now() > lastUpdatedTime;
2019-10-05 02:09:52 +02:00
},
};