YesPlayMusic/packages/web/api/hooks/usePlaylist.ts

66 lines
1.7 KiB
TypeScript
Raw Normal View History

2022-05-12 02:45:43 +08:00
import { fetchPlaylist } from '@/web/api/playlist'
import reactQueryClient from '@/web/utils/reactQueryClient'
2022-04-16 21:14:03 +08:00
import { IpcChannels } from '@/shared/IpcChannels'
2023-01-28 11:54:57 +08:00
import { CacheAPIs } from '@/shared/CacheAPIs'
2022-04-16 21:14:03 +08:00
import {
2022-04-09 00:28:37 +08:00
FetchPlaylistParams,
2022-04-16 21:14:03 +08:00
PlaylistApiNames,
2022-04-09 00:28:37 +08:00
FetchPlaylistResponse,
2022-04-16 21:14:03 +08:00
} from '@/shared/api/Playlists'
2022-08-03 23:48:39 +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 = (params: FetchPlaylistParams) => {
return fetchPlaylist(params)
2022-03-13 14:40:38 +08:00
}
2022-10-28 20:29:04 +08:00
export const fetchFromCache = async (
params: FetchPlaylistParams
): Promise<FetchPlaylistResponse | undefined> =>
window.ipcRenderer?.invoke(IpcChannels.GetApiCache, {
2023-01-28 11:54:57 +08:00
api: CacheAPIs.Playlist,
2022-10-28 20:29:04 +08:00
query: params,
2022-06-06 01:00:25 +08:00
})
2022-08-03 23:48:39 +08:00
export default function usePlaylist(params: FetchPlaylistParams) {
2022-10-28 20:29:04 +08:00
const key = [PlaylistApiNames.FetchPlaylist, params]
2022-03-13 14:40:38 +08:00
return useQuery(
2022-10-28 20:29:04 +08:00
key,
async () => {
// fetch from cache as placeholder
fetchFromCache(params).then(cache => {
const existsQueryData = reactQueryClient.getQueryData(key)
if (!existsQueryData && cache) {
reactQueryClient.setQueryData(key, cache)
}
})
return fetch(params)
},
2022-03-13 14:40:38 +08:00
{
enabled: !!(params.id && params.id > 0 && !isNaN(Number(params.id))),
2022-03-21 02:03:25 +08:00
refetchOnWindowFocus: true,
2022-03-13 14:40:38 +08:00
}
)
}
2022-04-02 18:46:08 +08:00
export function fetchPlaylistWithReactQuery(params: FetchPlaylistParams) {
return reactQueryClient.fetchQuery(
[PlaylistApiNames.FetchPlaylist, params],
2022-04-02 18:46:08 +08:00
() => fetch(params),
{
staleTime: 3600000,
}
)
}
2022-03-13 14:40:38 +08:00
export async function prefetchPlaylist(params: FetchPlaylistParams) {
2022-10-28 20:29:04 +08:00
if (await fetchFromCache(params)) return
2022-03-13 14:40:38 +08:00
await reactQueryClient.prefetchQuery(
[PlaylistApiNames.FetchPlaylist, params],
2022-03-13 14:40:38 +08:00
() => fetch(params),
{
staleTime: 3600000,
}
)
}