taevas.xyz/netlify/functions/anilist.ts

83 lines
2.4 KiB
TypeScript
Raw Normal View History

import {type Handler} from "@netlify/functions";
import fetch from "node-fetch";
import {type AnilistInfo} from "../../src/components/Info/Anilist.js";
2023-05-09 14:14:28 +02:00
2023-11-05 21:01:24 +01:00
const handler: Handler = async () => {
const anilist = await fetch("https://graphql.anilist.co", {
2023-05-09 14:14:28 +02:00
method: "POST",
headers: {
"Content-Type": "application/json",
2024-04-27 21:22:48 +02:00
// eslint-disable-next-line @typescript-eslint/naming-convention
"Accept": "application/json",
2023-05-09 14:14:28 +02:00
},
body: JSON.stringify({
query: `
query ($userName: String) {
MediaList (userName: $userName, type: ANIME, startedAt_greater: 1, sort: UPDATED_TIME_DESC) {
2023-05-09 14:14:28 +02:00
media {
title {
romaji
}
episodes
coverImage {
medium
}
2023-05-14 14:26:27 +02:00
siteUrl
2023-05-09 14:14:28 +02:00
}
progress
score (format: POINT_10)
startedAt {
day
month
year
}
updatedAt
completedAt {
day
month
year
}
}
}
`,
variables: {
userName: "Taevas",
},
}),
});
2023-05-09 14:14:28 +02:00
if (anilist.status !== 200) {
// log the issue in netlify, return 404 to the user anyway
console.log(await anilist.json());
2023-05-09 14:14:28 +02:00
return {
statusCode: 404,
body: "",
};
2023-05-09 14:14:28 +02:00
}
2024-04-27 21:22:48 +02:00
const json = (await anilist.json() as any).data.MediaList;
2023-11-05 21:01:24 +01:00
const anime: AnilistInfo = {
2023-05-09 14:14:28 +02:00
title: json.media.title.romaji,
episodes: {
watched: json.progress,
total: json.media.episodes,
},
score: json.score,
2023-10-31 00:12:55 +01:00
startDate: json.startedAt.year ? new Date(`${json.startedAt.year}-${json.startedAt.month}-${json.startedAt.day}`).toISOString() : new Date().toISOString(),
2023-05-09 14:14:28 +02:00
updateDate: new Date(json.updatedAt * 1000).toISOString(),
2023-10-31 00:12:55 +01:00
endDate: json.completedAt.year ? new Date(`${json.completedAt.year}-${json.completedAt.month}-${json.completedAt.day}`).toISOString() : new Date().toISOString(),
2023-05-14 14:26:27 +02:00
cover: json.media.coverImage.medium,
url: json.media.siteUrl,
};
2023-05-14 14:26:27 +02:00
anime.startDate = anime.startDate.substring(0, anime.startDate.indexOf("T"));
anime.updateDate = anime.updateDate.substring(0, anime.updateDate.indexOf("T"));
anime.endDate = anime.endDate.substring(0, anime.endDate.indexOf("T"));
2023-05-09 14:14:28 +02:00
return {
statusCode: 200,
body: JSON.stringify(anime),
};
};
2023-05-09 14:14:28 +02:00
export {handler};