aboutsummaryrefslogtreecommitdiff
path: root/lib/anilist/aniAdvanceSearch.js
blob: 02a5c53e1fb03416344f59b2ba9fcdcfa9f4dd38 (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
import { advanceSearchQuery } from "../graphql/query";

export async function aniAdvanceSearch({
  search,
  type,
  genres,
  page,
  sort,
  format,
  season,
  seasonYear,
  perPage,
}) {
  const categorizedGenres = genres?.reduce((result, item) => {
    const existingEntry = result[item.type];

    if (existingEntry) {
      existingEntry.push(item.value);
    } else {
      result[item.type] = [item.value];
    }

    return result;
  }, {});

  const response = await fetch("https://graphql.anilist.co/", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      query: advanceSearchQuery,
      variables: {
        ...(search && {
          search: search,
          ...(!sort && { sort: "SEARCH_MATCH" }),
        }),
        ...(type && { type: type }),
        ...(seasonYear && { seasonYear: seasonYear }),
        ...(season && {
          season: season,
          ...(!seasonYear && { seasonYear: new Date().getFullYear() }),
        }),
        ...(categorizedGenres && { ...categorizedGenres }),
        ...(format && { format: format }),
        // ...(genres && { genres: genres }),
        // ...(tags && { tags: tags }),
        ...(perPage && { perPage: perPage }),
        ...(sort && { sort: sort }),
        ...(page && { page: page }),
      },
    }),
  });

  const datas = await response.json();
  // console.log(datas);
  const data = datas.data.Page;
  return data;
}