aboutsummaryrefslogtreecommitdiff
path: root/lib/anilist/getUpcomingAnime.js
blob: 2ab931526700a25c0fa2b65d54243467159cf3b8 (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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, $year: Int, $format: MediaFormat, $excludeFormat: MediaFormat, $status: MediaStatus, $minEpisodes: Int, $page: Int) {
      Page(page: $page) {
        pageInfo {
          hasNextPage
          total
        }
        media(season: $season, seasonYear: $year, format: $format, format_not: $excludeFormat, status: $status, episodes_greater: $minEpisodes, isAdult: false, type: ANIME, sort: TITLE_ROMAJI) {
          id
          idMal
          title {
            romaji
            native
            english
          }
          startDate {
            year
            month
            day
          }
          status
          season
          format
          description
          bannerImage
          coverImage {
            extraLarge
            color
          }
          airingSchedule(notYetAired: true, perPage: 1) {
            nodes {
              episode
              airingAt
            }
          }
        }
      }
    }
  `;

  const variables = {
    season: "FALL",
    year: currentYear,
    format: "TV",
  };

  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.airingSchedule.nodes?.[0]?.episode === 1
  );

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

  return null;
};

export default getUpcomingAnime;