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,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,4 @@
|
||||
import { graphql } from "gql.tada";
|
||||
import { GraphQLClient } from "graphql-request";
|
||||
|
||||
import { sleep } from "../sleep";
|
||||
|
||||
const GetNextEpisodeAiringAtQuery = graphql(`
|
||||
query GetNextEpisodeAiringAt($id: Int!) {
|
||||
Media(id: $id) {
|
||||
status
|
||||
nextAiringEpisode {
|
||||
episode
|
||||
airingAt
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
import { env } from "cloudflare:workers";
|
||||
|
||||
type NextAiringTime = {
|
||||
status:
|
||||
@@ -32,26 +17,30 @@ type NextAiringTime = {
|
||||
export async function getNextEpisodeTimeUntilAiring(
|
||||
aniListId: number,
|
||||
): Promise<NextAiringTime> {
|
||||
const client = new GraphQLClient("https://graphql.anilist.co/");
|
||||
const durableObjectId = env.ANILIST_DO.idFromName(aniListId.toString());
|
||||
const stub = env.ANILIST_DO.get(durableObjectId);
|
||||
|
||||
try {
|
||||
const { status, nextAiringEpisode: nextAiring } = await client
|
||||
.request(GetNextEpisodeAiringAtQuery, {
|
||||
id: aniListId,
|
||||
})
|
||||
.then((data) => data!.Media!);
|
||||
const response = await stub.fetch("http://anilist-do/graphql", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
operationName: "GetNextEpisodeAiringAt",
|
||||
variables: { id: aniListId },
|
||||
}),
|
||||
});
|
||||
|
||||
return { status, nextAiring };
|
||||
} catch (error) {
|
||||
if (error.response.status === 429) {
|
||||
console.log(
|
||||
"429, retrying in",
|
||||
error.response.headers.get("Retry-After"),
|
||||
);
|
||||
await sleep(Number(error.response.headers.get("Retry-After")!) * 1000);
|
||||
return getNextEpisodeTimeUntilAiring(aniListId);
|
||||
}
|
||||
|
||||
throw error;
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch next episode airing time: ${response.statusText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as any;
|
||||
|
||||
return {
|
||||
status: data?.status,
|
||||
nextAiring: data?.nextAiringEpisode,
|
||||
};
|
||||
}
|
||||
|
||||
259
src/libs/anilist/queries.ts
Normal file
259
src/libs/anilist/queries.ts
Normal file
@@ -0,0 +1,259 @@
|
||||
import { graphql } from "gql.tada";
|
||||
|
||||
import { HomeTitleFragment } from "~/types/title/homeTitle";
|
||||
import { MediaFragment } from "~/types/title/mediaFragment";
|
||||
|
||||
export const GetTitleQuery = graphql(
|
||||
`
|
||||
query GetTitle($id: Int!) {
|
||||
Media(id: $id) {
|
||||
...Media
|
||||
}
|
||||
}
|
||||
`,
|
||||
[MediaFragment],
|
||||
);
|
||||
|
||||
export const SearchQuery = graphql(
|
||||
`
|
||||
query Search($query: String!, $page: Int!, $limit: Int!) {
|
||||
Page(page: $page, perPage: $limit) {
|
||||
media(
|
||||
search: $query
|
||||
type: ANIME
|
||||
sort: [POPULARITY_DESC, SCORE_DESC]
|
||||
) {
|
||||
...HomeTitle
|
||||
}
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[HomeTitleFragment],
|
||||
);
|
||||
|
||||
export const GetNextEpisodeAiringAtQuery = graphql(`
|
||||
query GetNextEpisodeAiringAt($id: Int!) {
|
||||
Media(id: $id) {
|
||||
status
|
||||
nextAiringEpisode {
|
||||
episode
|
||||
airingAt
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
export const MarkEpisodeAsWatchedMutation = graphql(`
|
||||
mutation MarkEpisodeAsWatched($titleId: Int!, $episodeNumber: Int!) {
|
||||
SaveMediaListEntry(
|
||||
mediaId: $titleId
|
||||
status: CURRENT
|
||||
progress: $episodeNumber
|
||||
) {
|
||||
user {
|
||||
id
|
||||
name
|
||||
avatar {
|
||||
medium
|
||||
large
|
||||
}
|
||||
statistics {
|
||||
anime {
|
||||
minutesWatched
|
||||
episodesWatched
|
||||
count
|
||||
meanScore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
export const MarkTitleAsWatchedMutation = graphql(`
|
||||
mutation MarkTitleAsWatched($titleId: Int!) {
|
||||
SaveMediaListEntry(mediaId: $titleId, status: COMPLETED) {
|
||||
user {
|
||||
id
|
||||
name
|
||||
avatar {
|
||||
medium
|
||||
large
|
||||
}
|
||||
statistics {
|
||||
anime {
|
||||
minutesWatched
|
||||
episodesWatched
|
||||
count
|
||||
meanScore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
export const GetUserQuery = graphql(`
|
||||
query GetUser {
|
||||
Viewer {
|
||||
id
|
||||
name
|
||||
avatar {
|
||||
medium
|
||||
large
|
||||
}
|
||||
statistics {
|
||||
anime {
|
||||
minutesWatched
|
||||
episodesWatched
|
||||
count
|
||||
meanScore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
export const GetPopularTitlesQuery = graphql(
|
||||
`
|
||||
query GetPopularTitles(
|
||||
$page: Int
|
||||
$limit: Int
|
||||
$season: MediaSeason
|
||||
$seasonYear: Int
|
||||
) {
|
||||
Page(page: $page, perPage: $limit) {
|
||||
media(
|
||||
type: ANIME
|
||||
sort: POPULARITY_DESC
|
||||
season: $season
|
||||
seasonYear: $seasonYear
|
||||
isAdult: false
|
||||
) {
|
||||
...HomeTitle
|
||||
}
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[HomeTitleFragment],
|
||||
);
|
||||
|
||||
export const GetTrendingTitlesQuery = graphql(
|
||||
`
|
||||
query GetTrendingTitles($page: Int, $limit: Int) {
|
||||
Page(page: $page, perPage: $limit) {
|
||||
media(type: ANIME, sort: TRENDING_DESC, isAdult: false) {
|
||||
...HomeTitle
|
||||
}
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[HomeTitleFragment],
|
||||
);
|
||||
|
||||
export const GetUpcomingTitlesQuery = graphql(
|
||||
`
|
||||
query GetUpcomingTitles(
|
||||
$page: Int!
|
||||
$airingAtLowerBound: Int!
|
||||
$airingAtUpperBound: Int!
|
||||
) {
|
||||
Page(page: $page) {
|
||||
airingSchedules(
|
||||
notYetAired: true
|
||||
sort: TIME
|
||||
airingAt_lesser: $airingAtUpperBound
|
||||
airingAt_greater: $airingAtLowerBound
|
||||
) {
|
||||
id
|
||||
airingAt
|
||||
timeUntilAiring
|
||||
episode
|
||||
media {
|
||||
...Media
|
||||
}
|
||||
}
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[MediaFragment],
|
||||
);
|
||||
|
||||
export const BrowsePopularQuery = graphql(
|
||||
`
|
||||
query BrowsePopular(
|
||||
$season: MediaSeason!
|
||||
$seasonYear: Int!
|
||||
$nextSeason: MediaSeason!
|
||||
$nextYear: Int!
|
||||
$limit: Int!
|
||||
) {
|
||||
trending: Page(page: 1, perPage: $limit) {
|
||||
media(sort: TRENDING_DESC, type: ANIME, isAdult: false) {
|
||||
...HomeTitle
|
||||
}
|
||||
}
|
||||
season: Page(page: 1, perPage: $limit) {
|
||||
media(
|
||||
season: $season
|
||||
seasonYear: $seasonYear
|
||||
sort: POPULARITY_DESC
|
||||
type: ANIME
|
||||
isAdult: false
|
||||
) {
|
||||
...HomeTitle
|
||||
}
|
||||
}
|
||||
nextSeason: Page(page: 1, perPage: 1) {
|
||||
media(
|
||||
season: $nextSeason
|
||||
seasonYear: $nextYear
|
||||
sort: START_DATE_DESC
|
||||
type: ANIME
|
||||
isAdult: false
|
||||
) {
|
||||
nextAiringEpisode {
|
||||
airingAt
|
||||
timeUntilAiring
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[HomeTitleFragment],
|
||||
);
|
||||
|
||||
export const NextSeasonPopularQuery = graphql(
|
||||
`
|
||||
query NextSeasonPopular(
|
||||
$nextSeason: MediaSeason
|
||||
$nextYear: Int
|
||||
$limit: Int!
|
||||
) {
|
||||
Page(page: 1, perPage: $limit) {
|
||||
media(
|
||||
season: $nextSeason
|
||||
seasonYear: $nextYear
|
||||
sort: POPULARITY_DESC
|
||||
type: ANIME
|
||||
isAdult: false
|
||||
) {
|
||||
...HomeTitle
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[HomeTitleFragment],
|
||||
);
|
||||
Reference in New Issue
Block a user