aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Data/AniList/following.ts
blob: 60bb3ccc8b0e65d235c5b6934c6b5341208323ba (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
import { user, type User } from "./user";

export interface FollowingPage {
	data: {
		Page: {
			pageInfo: {
				hasNextPage: boolean;
			};
			following: Partial<User>[];
		};
	};
}

const followingPage = async (
	page: number,
	id: number,
): Promise<FollowingPage> =>
	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 }
						following(userId: ${id}) { name id }
					}
				}`,
			}),
		})
	).json();

export const followers = async (name: string): Promise<Partial<User>[]> => {
	const activities = [];
	let page = 1;
	const userData = await user(name);

	if (!userData) throw new Error(`User not found: ${name}`);

	const id = userData.id;
	let currentPage = await followingPage(page, id);

	for (const activity of currentPage.data.Page.following)
		activities.push(activity);

	while (currentPage["data"]["Page"]["pageInfo"]["hasNextPage"]) {
		for (const activity of currentPage.data.Page.following)
			activities.push(activity);

		page += 1;
		currentPage = await followingPage(page, id);
	}

	for (const activity of currentPage.data.Page.following)
		activities.push(activity);

	for (let i = activities.length - 1; i > 0; i--) {
		const j = Math.floor(Math.random() * (i + 1));
		[activities[i], activities[j]] = [activities[j], activities[i]];
	}

	return activities;
};