feat: Centralize Anilist GraphQL queries, generalize Durable Object for multiple operations with caching, and add new controllers for search, popular titles, user data, and episode tracking.
This commit is contained in:
@@ -1,51 +1,33 @@
|
||||
import { graphql } from "gql.tada";
|
||||
import { GraphQLClient } from "graphql-request";
|
||||
import { env } from "cloudflare:workers";
|
||||
|
||||
import { sleep } from "~/libs/sleep";
|
||||
import type { User } from "~/types/user";
|
||||
|
||||
const GetUserQuery = graphql(`
|
||||
query GetUser {
|
||||
Viewer {
|
||||
id
|
||||
name
|
||||
avatar {
|
||||
medium
|
||||
large
|
||||
}
|
||||
statistics {
|
||||
anime {
|
||||
minutesWatched
|
||||
episodesWatched
|
||||
count
|
||||
meanScore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
export async function getUser(aniListToken: string): Promise<User> {
|
||||
const client = new GraphQLClient("https://graphql.anilist.co/");
|
||||
const durableObjectId = env.ANILIST_DO.idFromName("GLOBAL");
|
||||
const stub = env.ANILIST_DO.get(durableObjectId);
|
||||
|
||||
try {
|
||||
const data = await client.request(GetUserQuery, undefined, {
|
||||
Authorization: `Bearer ${aniListToken}`,
|
||||
});
|
||||
return {
|
||||
...data?.Viewer,
|
||||
statistics: { ...data?.Viewer?.statistics?.anime },
|
||||
};
|
||||
} catch (err) {
|
||||
if (err.response?.status === 401) {
|
||||
const response = await stub.fetch("http://anilist-do/graphql", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
operationName: "GetUser",
|
||||
variables: { token: aniListToken },
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) {
|
||||
return null;
|
||||
} else if (err.response?.status === 429) {
|
||||
console.log("429, retrying in", err.response.headers.get("Retry-After"));
|
||||
return sleep(
|
||||
Number(err.response.headers.get("Retry-After")!) * 1000,
|
||||
).then(() => getUser(aniListToken));
|
||||
}
|
||||
|
||||
throw err;
|
||||
throw new Error(`Failed to fetch user: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as any;
|
||||
|
||||
return {
|
||||
...data,
|
||||
statistics: { ...data?.statistics?.anime },
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user