import type { Media, MediaTitle } from "./media"; interface SchedulePage { data: { Page: { media: { title: MediaTitle; synonyms: string[]; id: number; idMal: number; episodes: number; nextAiringEpisode?: { episode: number; airingAt?: number; }; coverImage: { extraLarge: string; medium: string; }; }[]; pageInfo: { hasNextPage: boolean; }; }; }; } const schedulePage = async ( page: number, year: number, season: "WINTER" | "SPRING" | "SUMMER" | "FALL", ): Promise => await ( await fetch("https://graphql.anilist.co", { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", }, body: JSON.stringify({ query: `{ Page(page: ${page}) { pageInfo { hasNextPage } media(season: ${season}, seasonYear: ${year}) { id idMal episodes synonyms title { english romaji native } nextAiringEpisode { episode airingAt } coverImage { extraLarge medium } } } }`, }), }) ).json(); type Season = "WINTER" | "SPRING" | "SUMMER" | "FALL"; export const scheduleMediaListCollection = async ( year: number, season: Season, includeLastSeason = false, ) => { const scheduledMedia = []; let page = 1; let currentPage = await schedulePage(page, year, season); for (const candidate of currentPage.data.Page.media) scheduledMedia.push(candidate); while (currentPage["data"]["Page"]["pageInfo"]["hasNextPage"]) { for (const candidate of currentPage.data.Page.media) scheduledMedia.push(candidate); page += 1; currentPage = await schedulePage(page, year, season); } for (const candidate of currentPage.data.Page.media) scheduledMedia.push(candidate); if (includeLastSeason) { const lastSeason = { WINTER: "FALL", SPRING: "WINTER", SUMMER: "SPRING", FALL: "SUMMER", }[season]; const lastSeasonYear = season === "WINTER" ? year - 1 : year; let page = 1; let currentPage = await schedulePage( page, lastSeasonYear, lastSeason as Season, ); for (const candidate of currentPage.data.Page.media) scheduledMedia.push(candidate); while (currentPage["data"]["Page"]["pageInfo"]["hasNextPage"]) { for (const candidate of currentPage.data.Page.media) scheduledMedia.push(candidate); page += 1; currentPage = await schedulePage( page, lastSeasonYear, lastSeason as Season, ); } for (const candidate of currentPage.data.Page.media) scheduledMedia.push(candidate); } return scheduledMedia as Partial; };