2022-11-24 14:47:14 +09:00
|
|
|
import LRU from 'lru-cache'
|
|
|
|
import type { Account, Status } from 'masto'
|
|
|
|
|
|
|
|
const cache = new LRU<string, any>({
|
|
|
|
max: 1000,
|
|
|
|
})
|
|
|
|
|
|
|
|
if (process.dev)
|
|
|
|
// eslint-disable-next-line no-console
|
|
|
|
console.log({ cache })
|
|
|
|
|
2022-11-24 16:53:27 +09:00
|
|
|
export function setCached(key: string, value: any, override = false) {
|
|
|
|
if (override || !cache.has(key))
|
|
|
|
cache.set(key, value)
|
2022-11-24 14:47:14 +09:00
|
|
|
}
|
|
|
|
|
2022-11-25 00:48:52 +09:00
|
|
|
export function fetchStatus(id: string): Promise<Status> {
|
2022-11-24 14:47:14 +09:00
|
|
|
const key = `status:${id}`
|
|
|
|
const cached = cache.get(key)
|
|
|
|
if (cached)
|
|
|
|
return cached
|
2022-11-27 00:42:58 +09:00
|
|
|
const promise = useMasto().statuses.fetch(id)
|
2022-11-24 14:47:14 +09:00
|
|
|
.then((status) => {
|
|
|
|
cacheStatus(status)
|
|
|
|
return status
|
|
|
|
})
|
|
|
|
cache.set(key, promise)
|
|
|
|
return promise
|
|
|
|
}
|
|
|
|
|
2022-11-30 16:08:10 +09:00
|
|
|
export function fetchAccountById(id: string): Promise<Account> {
|
2022-11-24 14:47:14 +09:00
|
|
|
const key = `account:${id}`
|
|
|
|
const cached = cache.get(key)
|
|
|
|
if (cached)
|
|
|
|
return cached
|
2022-11-27 00:42:58 +09:00
|
|
|
const promise = useMasto().accounts.fetch(id)
|
2022-11-24 14:47:14 +09:00
|
|
|
.then((account) => {
|
2022-11-24 16:53:27 +09:00
|
|
|
cacheAccount(account, true)
|
2022-11-24 14:47:14 +09:00
|
|
|
return account
|
|
|
|
})
|
|
|
|
cache.set(key, promise)
|
|
|
|
return promise
|
|
|
|
}
|
|
|
|
|
2022-11-30 16:08:10 +09:00
|
|
|
export async function fetchAccountByHandle(acct: string): Promise<Account> {
|
2022-11-24 14:47:14 +09:00
|
|
|
const key = `account:${acct}`
|
|
|
|
const cached = cache.get(key)
|
|
|
|
if (cached)
|
|
|
|
return cached
|
2022-11-27 00:42:58 +09:00
|
|
|
const account = useMasto().accounts.lookup({ acct })
|
2022-11-24 14:47:14 +09:00
|
|
|
.then((r) => {
|
2022-11-24 16:53:27 +09:00
|
|
|
cacheAccount(r, true)
|
2022-11-24 14:47:14 +09:00
|
|
|
return r
|
|
|
|
})
|
|
|
|
cache.set(key, account)
|
|
|
|
return account
|
|
|
|
}
|
|
|
|
|
2022-11-30 16:08:10 +09:00
|
|
|
export function useAccountByHandle(acct: string) {
|
|
|
|
return useAsyncState(() => fetchAccountByHandle(acct), null).state
|
|
|
|
}
|
|
|
|
|
|
|
|
export function useAccountById(id: string) {
|
|
|
|
return useAsyncState(() => fetchAccountById(id), null).state
|
|
|
|
}
|
|
|
|
|
2022-11-24 16:53:27 +09:00
|
|
|
export function cacheStatus(status: Status, override?: boolean) {
|
|
|
|
setCached(`status:${status.id}`, status, override)
|
2022-11-24 14:47:14 +09:00
|
|
|
}
|
|
|
|
|
2022-11-24 16:53:27 +09:00
|
|
|
export function cacheAccount(account: Account, override?: boolean) {
|
|
|
|
setCached(`account:${account.id}`, account, override)
|
|
|
|
setCached(`account:${account.acct}`, account, override)
|
2022-11-24 14:47:14 +09:00
|
|
|
}
|