aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Data/AniList/identity.ts
blob: 973e1184a7da1d052033ab41ac9e29a03d6c2a7e (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
export interface UserIdentity {
	id: number;
	name: string;
	avatar: string;
}

export interface AniListAuthorisation {
	tokenType: string;
	accessToken: string;
	expiresIn: number;
	refreshToken: string;
}

export const userIdentity = async (
	anilistAuthorisation: AniListAuthorisation,
): Promise<UserIdentity> => {
	const userIdResponse = await (
		await fetch("https://graphql.anilist.co", {
			method: "POST",
			headers: {
				Authorization: `${anilistAuthorisation.tokenType} ${anilistAuthorisation.accessToken}`,
				"Content-Type": "application/json",
				Accept: "application/json",
			},
			body: JSON.stringify({
				query: `{ Viewer { id name avatar { large } } }`,
			}),
		})
	).json();

	return {
		id: userIdResponse["data"]["Viewer"]["id"],
		name: userIdResponse["data"]["Viewer"]["name"],
		avatar: userIdResponse["data"]["Viewer"]["avatar"]["large"],
	};
};

export const safeUserIdentity = async (
	anilistAuthorisation: AniListAuthorisation,
): Promise<UserIdentity | null> => {
	try {
		const identity = await userIdentity(anilistAuthorisation);

		if (!identity.id || !identity.name || !identity.avatar) return null;

		return identity;
	} catch {
		return null;
	}
};