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:
2025-11-29 05:03:57 -05:00
parent a25111acbf
commit b1e46ad6eb
10 changed files with 726 additions and 520 deletions

View File

@@ -1,22 +1,22 @@
import { DurableObject, env } from "cloudflare:workers";
import { graphql, type ResultOf } from "gql.tada";
import { type ResultOf } from "gql.tada";
import { print } from "graphql";
import { z } from "zod";
import {
BrowsePopularQuery,
GetNextEpisodeAiringAtQuery,
GetPopularTitlesQuery,
GetTitleQuery,
GetTrendingTitlesQuery,
GetUpcomingTitlesQuery,
GetUserQuery,
MarkEpisodeAsWatchedMutation,
MarkTitleAsWatchedMutation,
NextSeasonPopularQuery,
SearchQuery,
} from "~/libs/anilist/queries";
import { sleep } from "~/libs/sleep.ts";
import type { Title } from "~/types/title";
import { MediaFragment } from "~/types/title/mediaFragment";
const GetTitleQuery = graphql(
`
query GetTitle($id: Int!) {
Media(id: $id) {
...Media
}
}
`,
[MediaFragment],
);
const nextAiringEpisodeSchema = z.nullable(
z.object({
@@ -35,12 +35,38 @@ export class AnilistDurableObject extends DurableObject {
}
async fetch(request: Request) {
const body = await request.json();
const { operationName } = body;
const body = (await request.json()) as any;
const { operationName, variables } = body;
// Helper to handle caching logic
const handleCachedRequest = async (
key: string,
fetcher: () => Promise<any>,
ttl?: number,
) => {
const cache = await this.state.storage.get(key);
if (cache) {
return new Response(JSON.stringify(cache), {
headers: { "Content-Type": "application/json" },
});
}
const result = await fetcher();
await this.state.storage.put(key, result);
if (ttl) {
const alarmTime = Date.now() + ttl;
await this.state.storage.setAlarm(alarmTime);
await this.state.storage.put(`alarm:${key}`, alarmTime);
}
return new Response(JSON.stringify(result), {
headers: { "Content-Type": "application/json" },
});
};
switch (operationName) {
case "GetTitle": {
const { variables } = body;
const storageKey = variables.id;
const cache = await this.state.storage.get(storageKey);
if (cache) {
@@ -49,25 +75,173 @@ export class AnilistDurableObject extends DurableObject {
});
}
const anilistResponse = await this.fetchTitleFromAnilist(
variables.id,
const anilistResponse = await this.fetchFromAnilist(
GetTitleQuery,
variables,
variables.token,
);
// Extract next airing episode for alarm
// We need to cast or check the response structure because fetchFromAnilist returns generic data
const media = anilistResponse.Media as ResultOf<
typeof GetTitleQuery
>["Media"];
// Cast to any to access fragment fields without unmasking
const nextAiringEpisode = nextAiringEpisodeSchema.parse(
anilistResponse?.nextAiringEpisode,
(media as any)?.nextAiringEpisode,
);
const airingAt = (nextAiringEpisode?.airingAt ?? 0) * 1000;
await this.state.storage.put(storageKey, anilistResponse);
await this.state.storage.put(storageKey, media);
if (airingAt) {
await this.state.storage.setAlarm(airingAt);
await this.state.storage.put(`alarm:${variables.id}`, airingAt);
}
return new Response(JSON.stringify(anilistResponse), {
return new Response(JSON.stringify(media), {
headers: { "Content-Type": "application/json" },
});
}
case "GetNextEpisodeAiringAt": {
const storageKey = `next_airing:${variables.id}`;
// Cache for 1 hour or until airing?
// For now, let's cache for 1 hour as it might change
const TTL = 60 * 60 * 1000;
return handleCachedRequest(
storageKey,
async () => {
const data = await this.fetchFromAnilist(
GetNextEpisodeAiringAtQuery,
variables,
);
return data?.Media;
},
TTL,
);
}
case "Search": {
const storageKey = `search:${JSON.stringify(variables)}`;
const TTL = 60 * 60 * 1000; // 1 hour
return handleCachedRequest(
storageKey,
async () => {
const data = await this.fetchFromAnilist(SearchQuery, variables);
return data?.Page;
},
TTL,
);
}
case "BrowsePopular": {
const storageKey = `browse_popular:${JSON.stringify(variables)}`;
const TTL = 60 * 60 * 1000; // 1 hour
return handleCachedRequest(
storageKey,
async () => {
return this.fetchFromAnilist(BrowsePopularQuery, variables);
},
TTL,
);
}
case "NextSeasonPopular": {
const storageKey = `next_season:${JSON.stringify(variables)}`;
const TTL = 60 * 60 * 1000;
return handleCachedRequest(
storageKey,
async () => {
return this.fetchFromAnilist(NextSeasonPopularQuery, variables);
},
TTL,
);
}
case "GetPopularTitles": {
const storageKey = `popular:${JSON.stringify(variables)}`;
const TTL = 60 * 60 * 1000;
return handleCachedRequest(
storageKey,
async () => {
const data = await this.fetchFromAnilist(
GetPopularTitlesQuery,
variables,
);
return data?.Page;
},
TTL,
);
}
case "GetTrendingTitles": {
const storageKey = `trending:${JSON.stringify(variables)}`;
const TTL = 60 * 60 * 1000;
return handleCachedRequest(
storageKey,
async () => {
const data = await this.fetchFromAnilist(
GetTrendingTitlesQuery,
variables,
);
return data?.Page;
},
TTL,
);
}
case "GetUser": {
// No caching for user data for now, just rate limiting via DO
const data = await this.fetchFromAnilist(
GetUserQuery,
variables,
variables.token,
);
return new Response(JSON.stringify(data?.Viewer), {
headers: { "Content-Type": "application/json" },
});
}
case "MarkEpisodeAsWatched": {
const data = await this.fetchFromAnilist(
MarkEpisodeAsWatchedMutation,
variables,
variables.token,
);
return new Response(JSON.stringify(data?.SaveMediaListEntry), {
headers: { "Content-Type": "application/json" },
});
}
case "MarkTitleAsWatched": {
const data = await this.fetchFromAnilist(
MarkTitleAsWatchedMutation,
variables,
variables.token,
);
return new Response(JSON.stringify(data?.SaveMediaListEntry), {
headers: { "Content-Type": "application/json" },
});
}
case "GetUpcomingTitles": {
const storageKey = `upcoming:${JSON.stringify(variables)}`;
const TTL = 60 * 60 * 1000;
return handleCachedRequest(
storageKey,
async () => {
const data = await this.fetchFromAnilist(
GetUpcomingTitlesQuery,
variables,
);
return data?.Page;
},
TTL,
);
}
default:
return new Response("Not found", { status: 404 });
}
@@ -76,17 +250,22 @@ export class AnilistDurableObject extends DurableObject {
async alarm() {
const now = Date.now();
const alarms = await this.state.storage.list({ prefix: "alarm:" });
for (const [id, ttl] of Object.entries(alarms)) {
for (const [key, ttl] of Object.entries(alarms)) {
if (now >= ttl) {
await this.state.storage.delete(id);
// The key in alarms is `alarm:${storageKey}`
// We want to delete the storageKey
const storageKey = key.replace("alarm:", "");
await this.state.storage.delete(storageKey);
await this.state.storage.delete(key);
}
}
}
async fetchTitleFromAnilist(
id: number,
async fetchFromAnilist(
query: any,
variables: any,
token?: string | undefined,
): Promise<Title | undefined> {
): Promise<any> {
const headers: any = {
"Content-Type": "application/json",
};
@@ -95,6 +274,10 @@ export class AnilistDurableObject extends DurableObject {
headers["Authorization"] = `Bearer ${token}`;
}
// Use the query passed in, or fallback if needed (though we expect it to be passed)
// We print the query to string
const queryString = print(query);
const response = await fetch(`${env.PROXY_URL}/proxy`, {
method: "POST",
headers: {
@@ -105,9 +288,8 @@ export class AnilistDurableObject extends DurableObject {
method: "POST",
headers, // Pass the original headers here
data: {
operationName: "GetTitle",
query: print(GetTitleQuery),
variables: { id },
query: queryString,
variables,
},
}),
});
@@ -118,7 +300,7 @@ export class AnilistDurableObject extends DurableObject {
console.log("429, retrying in", retryAfter);
await sleep(Number(retryAfter || 1) * 1000); // specific fallback or ensure logic
return this.fetchTitleFromAnilist(id, token);
return this.fetchFromAnilist(query, variables, token);
}
// 2. Handle HTTP Errors (like 404 or 500)
@@ -134,9 +316,8 @@ export class AnilistDurableObject extends DurableObject {
}
// 3. Parse JSON
// We cast this to ResultOf<typeof GetTitleQuery> to maintain Tada type safety
const result = (await response.json().then((json) => json.data)) as {
data?: ResultOf<typeof GetTitleQuery>;
const result = (await response.json().then((json: any) => json.data)) as {
data?: any;
errors?: any[];
};
@@ -151,6 +332,6 @@ export class AnilistDurableObject extends DurableObject {
throw new Error(`GraphQL Error: ${errorMessage}`);
}
return result.data?.Media ?? undefined;
return result.data ?? undefined;
}
}