aboutsummaryrefslogtreecommitdiff
path: root/src/lib/AniList/following.ts
blob: 1bba66b928a506c69351fb411a9ac0ae6c5f0c86 (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
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 id = (await user(name)).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;
};