aboutsummaryrefslogtreecommitdiff
path: root/lib/anilist/getUpcomingAnime.js
blob: fc848fdd0ec5017093d2e14e08fe27dfbc54950e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const getUpcomingAnime = async () => {
  // Determine the current season and year
  const currentDate = new Date();
  const currentMonth = currentDate.getMonth();
  let currentSeason, currentYear;

  if (currentMonth < 3) {
    currentSeason = "WINTER";
    currentYear = currentDate.getFullYear();
  } else if (currentMonth < 6) {
    currentSeason = "SPRING";
    currentYear = currentDate.getFullYear();
  } else if (currentMonth < 9) {
    currentSeason = "SUMMER";
    currentYear = currentDate.getFullYear();
  } else {
    currentSeason = "FALL";
    currentYear = currentDate.getFullYear();
  }

  const query = `
    query ($season: MediaSeason, $seasonYear: Int) {
      Page(page: 1, perPage: 20) {
        media(season: $season, seasonYear: $seasonYear, sort: POPULARITY_DESC, type: ANIME) {
          id
          coverImage{
            large
          }
          bannerImage
          title {
            english
            romaji
            native
          }
          nextAiringEpisode {
            episode
            airingAt
            timeUntilAiring
          }
        }
      }
    }
  `;

  const variables = {
    season: currentSeason,
    seasonYear: currentYear,
  };

  let response = await fetch("https://graphql.anilist.co", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify({
      query,
      variables: variables ? variables : undefined,
    }),
  });

  let json = await response.json();

  let currentSeasonAnime = json.data.Page.media;
  let nextAiringAnime = currentSeasonAnime.filter(
    (anime) =>
      anime.nextAiringEpisode !== null && anime.nextAiringEpisode.episode === 1
  );

  if (nextAiringAnime.length >= 1) {
    nextAiringAnime.sort(
      (a, b) => a.nextAiringEpisode.airingAt - b.nextAiringEpisode.airingAt
    );
    return nextAiringAnime; // return all upcoming anime, not just the first two
  }

  return null;
};

export default getUpcomingAnime;