70 lines
1.7 KiB
TypeScript
Raw Normal View History

2022-05-12 02:45:43 +08:00
import { fetchAlbum } from '@/web/api/album'
import reactQueryClient from '@/web/utils/reactQueryClient'
2022-04-16 21:14:03 +08:00
import { IpcChannels } from '@/shared/IpcChannels'
import { APIs } from '@/shared/CacheAPIs'
import {
FetchAlbumParams,
AlbumApiNames,
FetchAlbumResponse,
} from '@/shared/api/Album'
2022-10-28 20:29:04 +08:00
import { useQuery } from '@tanstack/react-query'
2022-03-13 14:40:38 +08:00
2022-08-03 23:48:39 +08:00
const fetch = async (params: FetchAlbumParams) => {
const album = await fetchAlbum(params)
2022-03-13 14:40:38 +08:00
if (album?.album?.songs) {
album.album.songs = album.songs
}
return album
}
2022-10-28 20:29:04 +08:00
const fetchFromCache = async (
params: FetchAlbumParams
): Promise<FetchAlbumResponse | undefined> =>
window.ipcRenderer?.invoke(IpcChannels.GetApiCache, {
2022-06-06 01:00:25 +08:00
api: APIs.Album,
2022-08-03 23:48:39 +08:00
query: params,
2022-06-06 01:00:25 +08:00
})
2022-10-28 20:29:04 +08:00
export default function useAlbum(params: FetchAlbumParams) {
const key = [AlbumApiNames.FetchAlbum, params]
return useQuery(
key,
() => {
// fetch from cache as placeholder
fetchFromCache(params).then(cache => {
const existsQueryData = reactQueryClient.getQueryData(key)
if (!existsQueryData && cache) {
reactQueryClient.setQueryData(key, cache)
}
})
return fetch(params)
},
{
enabled: !!params.id,
staleTime: 24 * 60 * 60 * 1000, // 24 hours
}
)
2022-03-13 14:40:38 +08:00
}
2022-04-02 18:46:08 +08:00
export function fetchAlbumWithReactQuery(params: FetchAlbumParams) {
return reactQueryClient.fetchQuery(
2022-08-03 23:48:39 +08:00
[AlbumApiNames.FetchAlbum, params],
2022-04-02 18:46:08 +08:00
() => fetch(params),
{
staleTime: Infinity,
}
)
}
2022-03-13 14:40:38 +08:00
export async function prefetchAlbum(params: FetchAlbumParams) {
2022-10-28 20:29:04 +08:00
if (await fetchFromCache(params)) return
2022-03-13 14:40:38 +08:00
await reactQueryClient.prefetchQuery(
2022-08-03 23:48:39 +08:00
[AlbumApiNames.FetchAlbum, params],
2022-03-13 14:40:38 +08:00
() => fetch(params),
{
staleTime: Infinity,
}
)
}