-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathutilsStorage.ts
40 lines (32 loc) · 1.14 KB
/
utilsStorage.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import merge from 'lodash/merge'
import dayjs from '@ui-kit/lib/dayjs'
export const APP_STORAGE = {
APP_CACHE: 'dao-app-cache',
}
type Key = keyof typeof APP_STORAGE
export function getStorageValue(key: Key) {
const storedValue = window.localStorage.getItem(APP_STORAGE[key])
let parsedStoredValue: { [key: string]: string } = {}
if (storedValue) {
try {
parsedStoredValue = JSON.parse(storedValue) ?? {}
} catch (error) {
console.error(error)
}
}
if (key === 'APP_CACHE') {
return {
timestamp: parsedStoredValue.timestamp ?? '',
walletName: getWalletName(parsedStoredValue.walletName, parsedStoredValue.timestamp),
}
}
}
function getWalletName(walletName: string | undefined, timestamp: string | undefined) {
const isStaled = walletName && timestamp && dayjs().diff(+timestamp, 'days') > 5
return isStaled || !walletName ? '' : walletName
}
export function setStorageValue<T>(key: Key, updatedValue: T) {
const storedValue = getStorageValue(key)
const mergedStoredValue = merge(storedValue, updatedValue)
window.localStorage.setItem(APP_STORAGE[key], JSON.stringify(mergedStoredValue))
}