62 lines
1.6 KiB
TypeScript
Raw Normal View History

2022-05-12 02:45:43 +08:00
import { fetchArtist } from '@/web/api/artist'
2022-04-16 21:14:03 +08:00
import { IpcChannels } from '@/shared/IpcChannels'
import { APIs } from '@/shared/CacheAPIs'
import {
2022-04-09 00:28:37 +08:00
FetchArtistParams,
2022-04-16 21:14:03 +08:00
ArtistApiNames,
2022-04-09 00:28:37 +08:00
FetchArtistResponse,
2022-04-16 21:14:03 +08:00
} from '@/shared/api/Artist'
2022-08-03 23:48:39 +08:00
import { useQuery } from '@tanstack/react-query'
import reactQueryClient from '@/web/utils/reactQueryClient'
2022-03-13 14:40:38 +08:00
2022-10-28 20:29:04 +08:00
const fetchFromCache = async (
params: FetchArtistParams
): Promise<FetchArtistResponse | undefined> =>
window.ipcRenderer?.invoke(IpcChannels.GetApiCache, {
2022-08-03 23:48:39 +08:00
api: APIs.Artist,
2022-10-28 20:29:04 +08:00
query: params,
2022-08-03 23:48:39 +08:00
})
export default function useArtist(params: FetchArtistParams) {
2022-10-28 20:29:04 +08:00
const key = [ArtistApiNames.FetchArtist, params]
2022-03-13 14:40:38 +08:00
return useQuery(
2022-10-28 20:29:04 +08:00
key,
() => {
// fetch from cache as placeholder
fetchFromCache(params).then(cache => {
const existsQueryData = reactQueryClient.getQueryData(key)
if (!existsQueryData && cache) {
reactQueryClient.setQueryData(key, cache)
}
})
return fetchArtist(params)
},
2022-03-13 14:40:38 +08:00
{
enabled: !!params.id && params.id > 0 && !isNaN(Number(params.id)),
2022-03-23 01:21:22 +08:00
staleTime: 5 * 60 * 1000, // 5 mins
2022-08-03 23:48:39 +08:00
}
)
}
export function fetchArtistWithReactQuery(params: FetchArtistParams) {
return reactQueryClient.fetchQuery(
[ArtistApiNames.FetchArtist, params],
() => fetchArtist(params),
{
staleTime: Infinity,
}
)
}
export async function prefetchArtist(params: FetchArtistParams) {
2022-10-28 20:29:04 +08:00
if (await fetchFromCache(params)) return
2022-08-03 23:48:39 +08:00
await reactQueryClient.prefetchQuery(
[ArtistApiNames.FetchArtist, params],
() => fetchArtist(params),
{
staleTime: Infinity,
2022-03-13 14:40:38 +08:00
}
)
}