fix: add abort signal to prevent the loader from showing when switching from a long load page

This commit is contained in:
2024-04-21 21:49:22 +02:00
parent 05fd42d729
commit cff65c7516
3 changed files with 19 additions and 8 deletions

View File

@@ -1,7 +1,8 @@
class BypassCorsService {
async fetchBypassingCors(url: string) {
async fetchBypassingCors(url: string, init?: RequestInit) {
return await fetch(
`https://api.allorigins.win/raw?url=${encodeURIComponent(url)}`,
init,
);
}
}

View File

@@ -9,14 +9,15 @@ const QUERY_KEYS = {
export function useTopPodcastsQuery() {
return useQuery({
queryKey: [QUERY_KEYS.TOP_PODCASTS],
queryFn: () => podcastsService.getTopPodcasts(),
queryFn: ({ signal }) => podcastsService.getTopPodcasts({ signal }),
});
}
export function usePodcastQuery(podcastId?: string) {
return useQuery({
queryKey: [QUERY_KEYS.PODCAST_EPISODES, podcastId],
queryFn: () => podcastsService.getPodcastById(podcastId ?? ""),
queryFn: ({ signal }) =>
podcastsService.getPodcastById(podcastId ?? "", { signal }),
enabled: !!podcastId,
});
}

View File

@@ -7,16 +7,21 @@ import { bypassCorsService } from "../bypass-cors";
class PodcastsService {
baseUrl = "https://itunes.apple.com";
async getTopPodcasts(): Promise<PodcastDTO[]> {
async getTopPodcasts({
signal,
}: {
signal: AbortSignal;
}): Promise<PodcastDTO[]> {
const response = await fetch(
`${this.baseUrl}/us/rss/toppodcasts/limit=100/genre=1310/json`,
{ signal },
);
const data: GetTopPodcastsResponse = await response.json();
return data.feed.entry.map((podcast) => new PodcastDTO(podcast));
}
async getPodcastById(podcastId: string) {
async getPodcastById(podcastId: string, { signal }: { signal: AbortSignal }) {
try {
const url = new URL(`${this.baseUrl}/lookup`);
const params = {
@@ -30,11 +35,13 @@ class PodcastsService {
const response = await bypassCorsService.fetchBypassingCors(
url.toString(),
{ signal },
);
const json: GetEpisodesResponse = await response.json();
const podcastExtra = new PodcastExtraDTO(json.results[0]);
const podcastFromFeed = await this.getPodcastFeed(
json.results[0].feedUrl,
{ signal },
);
return { ...podcastExtra, ...podcastFromFeed };
} catch (error) {
@@ -43,11 +50,11 @@ class PodcastsService {
}
}
async getPodcastFeed(sourceURL: string) {
async getPodcastFeed(sourceURL: string, { signal }: { signal: AbortSignal }) {
let response: Response;
try {
response = await fetch(sourceURL);
response = await fetch(sourceURL, { signal });
if (!response.ok) {
throw new Error("CORS error or other network issue");
@@ -60,7 +67,9 @@ class PodcastsService {
try {
console.log("Attempting to fetch using CORS bypass...");
response = await bypassCorsService.fetchBypassingCors(sourceURL);
response = await bypassCorsService.fetchBypassingCors(sourceURL, {
signal,
});
const rss = await response.text();
return RssParser.parse(rss);
} catch (bypassError) {