2
2
mirror of https://github.com/Thream/website.git synced 2024-07-21 09:28:32 +02:00
website/tools/cache.ts
2022-08-30 18:42:21 +02:00

39 lines
980 B
TypeScript

import { PaginationItem } from '../hooks/usePagination'
export const GUILDS_CACHE_KEY = 'guilds' as const
export const CHANNELS_CACHE_KEY = 'channels' as const
export const MEMBERS_CACHE_KEY = 'members' as const
export const MESSAGES_CACHE_KEY = 'messages' as const
export type CacheKey =
| typeof GUILDS_CACHE_KEY
| `${number}-${typeof CHANNELS_CACHE_KEY}`
| `${number}-${typeof MEMBERS_CACHE_KEY}`
| `${number}-${typeof MESSAGES_CACHE_KEY}`
export const getPaginationCache = <T extends PaginationItem>(
key: CacheKey
): T[] => {
const cache = sessionStorage.getItem(key)
if (cache != null) {
try {
const data = JSON.parse(cache)
if (Array.isArray(data)) {
return data
}
} catch {}
}
return []
}
export const savePaginationCache = <T extends PaginationItem>(
key: CacheKey,
data: T[]
): void => {
sessionStorage.setItem(key, JSON.stringify(data))
}
export const clearCache = (): void => {
sessionStorage.clear()
}