aboutsummaryrefslogtreecommitdiff
path: root/lib/consumet/manga/getChapters.js
blob: ee6eabed2abe671576f3cb1fa0d511e5f2065c16 (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
let API_URL;
API_URL = process.env.API_URI || null || null;
// remove / from the end of the url if it exists
if (API_URL && API_URL.endsWith("/")) {
  API_URL = API_URL.slice(0, -1);
}

async function fetchInfo(id) {
  try {
    const providers = [
      "mangadex",
      "mangahere",
      "mangakakalot",
      // "mangapark",
      // "mangapill",
      "mangasee123",
    ];
    let datas = [];

    async function promiseMe(provider) {
      try {
        const data = await fetch(
          `${API_URL}/meta/anilist-manga/info/${id}?provider=${provider}`
        ).then((res) => {
          if (!res.ok) {
            switch (res.status) {
              case 404: {
                return null;
              }
            }
          }
          return res.json();
        });
        if (data.chapters.length > 0) {
          datas.push({
            providerId: provider,
            chapters: data.chapters,
          });
        }
      } catch (error) {
        console.error(`Error fetching data for provider '${provider}':`, error);
      }
    }

    await Promise.all(providers.map((provider) => promiseMe(provider)));

    return datas;
  } catch (error) {
    console.error("Error fetching data:", error);
    return null;
  }
}

export default async function getConsumetChapters(id, redis) {
  try {
    let cached;
    let chapters;

    if (redis) {
      cached = await redis.get(`chapter:${id}`);
    }

    if (cached) {
      chapters = JSON.parse(cached);
    } else {
      chapters = await fetchInfo(id);
    }

    if (chapters?.length === 0) {
      return null;
    }
    if (redis) {
      await redis.set(`chapter:${id}`, JSON.stringify(chapters), "EX", 60 * 60); // 1 hour
    }

    return chapters;
  } catch (error) {
    return { error };
  }
}