58 lines
1.5 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-08-22 16:51:23 +08:00
import { QueryOptions, 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-08-03 23:48:39 +08:00
const fetchFromCache = (params: FetchAlbumParams): FetchAlbumResponse =>
2022-06-06 01:00:25 +08:00
window.ipcRenderer?.sendSync(IpcChannels.GetApiCacheSync, {
api: APIs.Album,
2022-08-03 23:48:39 +08:00
query: params,
2022-06-06 01:00:25 +08:00
})
2022-08-22 16:51:23 +08:00
export default function useAlbum(
params: FetchAlbumParams
// queryOptions?: QueryOptions
) {
2022-08-03 23:48:39 +08:00
return useQuery([AlbumApiNames.FetchAlbum, params], () => fetch(params), {
enabled: !!params.id,
staleTime: 24 * 60 * 60 * 1000, // 24 hours
placeholderData: () => fetchFromCache(params),
2022-08-22 16:51:23 +08:00
// ...queryOptions,
2022-08-03 23:48:39 +08:00
})
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-08-03 23:48:39 +08:00
if (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,
}
)
}