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 },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,55 +1,4 @@
|
||||
import { graphql } from "gql.tada";
|
||||
import { GraphQLClient } from "graphql-request";
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
const MarkTitleAsWatchedMutation = graphql(`
|
||||
mutation MarkTitleAsWatched($titleId: Int!) {
|
||||
SaveMediaListEntry(mediaId: $titleId, status: COMPLETED) {
|
||||
user {
|
||||
id
|
||||
name
|
||||
avatar {
|
||||
medium
|
||||
large
|
||||
}
|
||||
statistics {
|
||||
anime {
|
||||
minutesWatched
|
||||
episodesWatched
|
||||
count
|
||||
meanScore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
import { env } from "cloudflare:workers";
|
||||
|
||||
export async function markEpisodeAsWatched(
|
||||
aniListToken: string,
|
||||
@@ -57,27 +6,38 @@ export async function markEpisodeAsWatched(
|
||||
episodeNumber: number,
|
||||
markTitleAsComplete: boolean,
|
||||
) {
|
||||
const client = new GraphQLClient("https://graphql.anilist.co/");
|
||||
const durableObjectId = env.ANILIST_DO.idFromName("GLOBAL");
|
||||
const stub = env.ANILIST_DO.get(durableObjectId);
|
||||
|
||||
const mutation = markTitleAsComplete
|
||||
? client.request(
|
||||
MarkTitleAsWatchedMutation,
|
||||
{ titleId },
|
||||
{ Authorization: `Bearer ${aniListToken}` },
|
||||
)
|
||||
: client.request(
|
||||
MarkEpisodeAsWatchedMutation,
|
||||
{ titleId, episodeNumber },
|
||||
{ Authorization: `Bearer ${aniListToken}` },
|
||||
);
|
||||
const operationName = markTitleAsComplete
|
||||
? "MarkTitleAsWatched"
|
||||
: "MarkEpisodeAsWatched";
|
||||
|
||||
return mutation
|
||||
.then((data) => ({
|
||||
...data?.SaveMediaListEntry?.user,
|
||||
statistics: data?.SaveMediaListEntry?.user?.statistics?.anime,
|
||||
}))
|
||||
.catch(async (err) => {
|
||||
console.error(await err.response);
|
||||
throw err;
|
||||
});
|
||||
const variables = markTitleAsComplete
|
||||
? { titleId, token: aniListToken }
|
||||
: { titleId, episodeNumber, token: aniListToken };
|
||||
|
||||
const response = await stub.fetch("http://anilist-do/graphql", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
operationName,
|
||||
variables,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to mark episode as watched: ${response.statusText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as any;
|
||||
|
||||
return {
|
||||
...data?.user,
|
||||
statistics: data?.user?.statistics?.anime,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { graphql } from "gql.tada";
|
||||
import { GraphQLClient } from "graphql-request";
|
||||
import { env } from "cloudflare:workers";
|
||||
import type { HonoRequest } from "hono";
|
||||
import { DateTime } from "luxon";
|
||||
|
||||
@@ -7,38 +6,6 @@ import { maybeScheduleNextAiringEpisode } from "~/libs/maybeScheduleNextAiringEp
|
||||
import { getValue, setValue } from "~/models/kv";
|
||||
import { filterUnreleasedTitles } from "~/models/unreleasedTitles";
|
||||
import type { Title } from "~/types/title";
|
||||
import { MediaFragment } from "~/types/title/mediaFragment";
|
||||
|
||||
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],
|
||||
);
|
||||
|
||||
type AiringSchedule = {
|
||||
media: Title;
|
||||
@@ -49,7 +16,9 @@ type AiringSchedule = {
|
||||
};
|
||||
|
||||
export async function getUpcomingTitlesFromAnilist(req: HonoRequest) {
|
||||
const client = new GraphQLClient("https://graphql.anilist.co/");
|
||||
const durableObjectId = env.ANILIST_DO.idFromName("GLOBAL");
|
||||
const stub = env.ANILIST_DO.get(durableObjectId);
|
||||
|
||||
const lastCheckedScheduleAt = await getValue("schedule_last_checked_at").then(
|
||||
(value) => (value ? Number(value) : DateTime.now().toUnixInteger()),
|
||||
);
|
||||
@@ -61,21 +30,38 @@ export async function getUpcomingTitlesFromAnilist(req: HonoRequest) {
|
||||
let shouldContinue = true;
|
||||
|
||||
do {
|
||||
const { Page } = await client.request(GetUpcomingTitlesQuery, {
|
||||
page: currentPage++,
|
||||
airingAtLowerBound: lastCheckedScheduleAt,
|
||||
airingAtUpperBound: twoDaysFromNow,
|
||||
const response = await stub.fetch("http://anilist-do/graphql", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
operationName: "GetUpcomingTitles",
|
||||
variables: {
|
||||
page: currentPage++,
|
||||
airingAtLowerBound: lastCheckedScheduleAt,
|
||||
airingAtUpperBound: twoDaysFromNow,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const { airingSchedules, pageInfo } = Page!;
|
||||
if (!response.ok) {
|
||||
// If failed, break loop or handle error. For now, break.
|
||||
break;
|
||||
}
|
||||
|
||||
const Page = (await response.json()) as any;
|
||||
if (!Page) break;
|
||||
|
||||
const { airingSchedules, pageInfo } = Page;
|
||||
plannedToWatchTitles = plannedToWatchTitles.union(
|
||||
await filterUnreleasedTitles(
|
||||
airingSchedules!.map((schedule) => schedule!.media?.id!),
|
||||
airingSchedules!.map((schedule: any) => schedule!.media?.id!),
|
||||
),
|
||||
);
|
||||
scheduleList = scheduleList.concat(
|
||||
airingSchedules!.filter(
|
||||
(schedule): schedule is AiringSchedule =>
|
||||
(schedule: any): schedule is AiringSchedule =>
|
||||
!!schedule &&
|
||||
!plannedToWatchTitles.has(schedule.media?.id) &&
|
||||
schedule.media?.countryOfOrigin === "JP" &&
|
||||
|
||||
@@ -1,157 +1,85 @@
|
||||
import { graphql } from "gql.tada";
|
||||
import { GraphQLClient } from "graphql-request";
|
||||
import { env } from "cloudflare:workers";
|
||||
|
||||
import { getCurrentAndNextSeason } from "~/libs/getCurrentAndNextSeason";
|
||||
import { sleep } from "~/libs/sleep";
|
||||
import { HomeTitleFragment } from "~/types/title/homeTitle";
|
||||
|
||||
import { mapTitle } from "../mapTitle";
|
||||
|
||||
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],
|
||||
);
|
||||
|
||||
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
|
||||
) {
|
||||
...media
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fragment media on Media {
|
||||
id
|
||||
title {
|
||||
english
|
||||
userPreferred
|
||||
}
|
||||
coverImage {
|
||||
extraLarge
|
||||
large
|
||||
medium
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
export async function fetchPopularTitlesFromAnilist(
|
||||
limit: number,
|
||||
): Promise<any> {
|
||||
const client = new GraphQLClient("https://graphql.anilist.co/");
|
||||
const durableObjectId = env.ANILIST_DO.idFromName("GLOBAL");
|
||||
const stub = env.ANILIST_DO.get(durableObjectId);
|
||||
|
||||
const {
|
||||
current: { season: currentSeason, year: currentYear },
|
||||
next: { season: nextSeason, year: nextYear },
|
||||
} = getCurrentAndNextSeason();
|
||||
|
||||
try {
|
||||
const data = await client.request(BrowsePopularQuery, {
|
||||
limit,
|
||||
season: currentSeason,
|
||||
seasonYear: currentYear,
|
||||
nextSeason,
|
||||
nextYear,
|
||||
});
|
||||
if (!data) return undefined;
|
||||
const response = await stub.fetch("http://anilist-do/graphql", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
operationName: "BrowsePopular",
|
||||
variables: {
|
||||
limit,
|
||||
season: currentSeason,
|
||||
seasonYear: currentYear,
|
||||
nextSeason,
|
||||
nextYear,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const trendingTitles = data.trending?.media?.map((title) =>
|
||||
mapTitle(title),
|
||||
);
|
||||
const popularSeasonTitles = data.season?.media?.map((title) =>
|
||||
mapTitle(title),
|
||||
);
|
||||
if (!response.ok) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (!data.nextSeason?.media?.[0]?.nextAiringEpisode) {
|
||||
return {
|
||||
trending: trendingTitles,
|
||||
popular: popularSeasonTitles,
|
||||
};
|
||||
}
|
||||
const data = (await response.json()) as any;
|
||||
if (!data) return undefined;
|
||||
|
||||
return await client
|
||||
.request(NextSeasonPopularQuery, {
|
||||
const trendingTitles = data.trending?.media?.map((title: any) =>
|
||||
mapTitle(title),
|
||||
);
|
||||
const popularSeasonTitles = data.season?.media?.map((title: any) =>
|
||||
mapTitle(title),
|
||||
);
|
||||
|
||||
if (!data.nextSeason?.media?.[0]?.nextAiringEpisode) {
|
||||
return {
|
||||
trending: trendingTitles,
|
||||
popular: popularSeasonTitles,
|
||||
};
|
||||
}
|
||||
|
||||
const nextSeasonResponse = await stub.fetch("http://anilist-do/graphql", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
operationName: "NextSeasonPopular",
|
||||
variables: {
|
||||
limit,
|
||||
nextSeason,
|
||||
nextYear,
|
||||
})
|
||||
.then((data) => ({
|
||||
trending: trendingTitles,
|
||||
popular: popularSeasonTitles,
|
||||
upcoming: data?.Page?.media?.map((title) => mapTitle(title)),
|
||||
}));
|
||||
} catch (error) {
|
||||
const response = error.response;
|
||||
if (response.status === 429) {
|
||||
console.log("429, retrying in", response.headers.get("Retry-After"));
|
||||
return sleep(Number(response.headers.get("Retry-After")!) * 1000).then(
|
||||
() => fetchPopularTitlesFromAnilist(limit),
|
||||
);
|
||||
}
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
throw error;
|
||||
if (!nextSeasonResponse.ok) {
|
||||
return {
|
||||
trending: trendingTitles,
|
||||
popular: popularSeasonTitles,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
type SearchResultsResponse = {
|
||||
results:
|
||||
| ({
|
||||
id: number;
|
||||
title: { userPreferred: string | null; english: string | null } | null;
|
||||
coverImage: {
|
||||
extraLarge: string | null;
|
||||
large: string | null;
|
||||
medium: string | null;
|
||||
} | null;
|
||||
} | null)[]
|
||||
| null;
|
||||
hasNextPage: boolean | null | undefined;
|
||||
};
|
||||
const nextSeasonData = (await nextSeasonResponse.json()) as any;
|
||||
|
||||
return {
|
||||
trending: trendingTitles,
|
||||
popular: popularSeasonTitles,
|
||||
upcoming: nextSeasonData?.Page?.media?.map((title: any) => mapTitle(title)),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,121 +1,66 @@
|
||||
import { graphql } from "gql.tada";
|
||||
import { GraphQLClient } from "graphql-request";
|
||||
import { env } from "cloudflare:workers";
|
||||
|
||||
import { getCurrentAndNextSeason } from "~/libs/getCurrentAndNextSeason";
|
||||
import { HomeTitleFragment } from "~/types/title/homeTitle";
|
||||
|
||||
import { mapTitle } from "../mapTitle";
|
||||
import type { PopularCategory } from "./enum";
|
||||
|
||||
const TrendingQuery = graphql(
|
||||
`
|
||||
query Trending($limit: Int!, $page: Int!) {
|
||||
trending: Page(page: $page, perPage: $limit) {
|
||||
media(sort: TRENDING_DESC, type: ANIME, isAdult: false) {
|
||||
...HomeTitle
|
||||
}
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[HomeTitleFragment],
|
||||
);
|
||||
|
||||
const PopularQuery = graphql(
|
||||
`
|
||||
query Popular(
|
||||
$limit: Int!
|
||||
$page: Int!
|
||||
$season: MediaSeason!
|
||||
$seasonYear: Int!
|
||||
) {
|
||||
Page(page: $page, perPage: $limit) {
|
||||
media(
|
||||
season: $season
|
||||
seasonYear: $seasonYear
|
||||
sort: POPULARITY_DESC
|
||||
type: ANIME
|
||||
isAdult: false
|
||||
) {
|
||||
...HomeTitle
|
||||
}
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[HomeTitleFragment],
|
||||
);
|
||||
|
||||
const UpcomingQuery = graphql(
|
||||
`
|
||||
query Upcoming(
|
||||
$limit: Int!
|
||||
$page: Int!
|
||||
$nextSeason: MediaSeason!
|
||||
$nextSeasonYear: Int!
|
||||
) {
|
||||
Page(page: $page, perPage: $limit) {
|
||||
media(
|
||||
season: $nextSeason
|
||||
seasonYear: $nextSeasonYear
|
||||
sort: POPULARITY_DESC
|
||||
type: ANIME
|
||||
isAdult: false
|
||||
) {
|
||||
...HomeTitle
|
||||
}
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[HomeTitleFragment],
|
||||
);
|
||||
|
||||
export function fetchPopularTitlesFromAnilist(
|
||||
export async function fetchPopularTitlesFromAnilist(
|
||||
category: PopularCategory,
|
||||
page: number,
|
||||
limit: number,
|
||||
) {
|
||||
const client = new GraphQLClient("https://graphql.anilist.co/");
|
||||
const durableObjectId = env.ANILIST_DO.idFromName("GLOBAL");
|
||||
const stub = env.ANILIST_DO.get(durableObjectId);
|
||||
|
||||
const { current, next } = getCurrentAndNextSeason();
|
||||
|
||||
let operationName = "";
|
||||
let variables: any = { limit, page };
|
||||
|
||||
switch (category) {
|
||||
case "trending":
|
||||
return client.request(TrendingQuery, { limit, page }).then((data) => ({
|
||||
results: data?.trending?.media?.map((title) => mapTitle(title)),
|
||||
hasNextPage: data?.trending?.pageInfo?.hasNextPage,
|
||||
}));
|
||||
operationName = "GetTrendingTitles";
|
||||
break;
|
||||
case "popular":
|
||||
return client
|
||||
.request(PopularQuery, {
|
||||
limit,
|
||||
page,
|
||||
season: current.season,
|
||||
seasonYear: current.year,
|
||||
})
|
||||
.then((data) => ({
|
||||
results: data?.Page?.media?.map((title) => mapTitle(title)),
|
||||
hasNextPage: data?.Page?.pageInfo?.hasNextPage,
|
||||
}));
|
||||
operationName = "GetPopularTitles";
|
||||
variables = {
|
||||
...variables,
|
||||
season: current.season,
|
||||
seasonYear: current.year,
|
||||
};
|
||||
break;
|
||||
case "upcoming":
|
||||
return client
|
||||
.request(UpcomingQuery, {
|
||||
limit,
|
||||
page,
|
||||
nextSeason: next.season,
|
||||
nextSeasonYear: next.year,
|
||||
})
|
||||
.then((data) => ({
|
||||
results: data?.Page?.media?.map((title) => mapTitle(title)),
|
||||
hasNextPage: data?.Page?.pageInfo?.hasNextPage,
|
||||
}));
|
||||
operationName = "NextSeasonPopular";
|
||||
variables = {
|
||||
...variables,
|
||||
nextSeason: next.season,
|
||||
nextYear: next.year,
|
||||
};
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Unknown category: ${category}`);
|
||||
}
|
||||
|
||||
const response = await stub.fetch("http://anilist-do/graphql", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
operationName,
|
||||
variables,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return { results: [], hasNextPage: false };
|
||||
}
|
||||
|
||||
const data = (await response.json()) as any;
|
||||
|
||||
return {
|
||||
results: data?.media?.map((title: any) => mapTitle(title)),
|
||||
hasNextPage: data?.pageInfo?.hasNextPage,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,69 +1,46 @@
|
||||
import { graphql } from "gql.tada";
|
||||
import { GraphQLClient } from "graphql-request";
|
||||
|
||||
import { sleep } from "~/libs/sleep";
|
||||
import { HomeTitleFragment } from "~/types/title/homeTitle";
|
||||
|
||||
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],
|
||||
);
|
||||
import { env } from "cloudflare:workers";
|
||||
|
||||
export async function fetchSearchResultsFromAnilist(
|
||||
query: string,
|
||||
page: number,
|
||||
limit: number,
|
||||
): Promise<SearchResultsResponse | undefined> {
|
||||
const client = new GraphQLClient("https://graphql.anilist.co/");
|
||||
const durableObjectId = env.ANILIST_DO.idFromName("GLOBAL");
|
||||
const stub = env.ANILIST_DO.get(durableObjectId);
|
||||
|
||||
return client
|
||||
.request(SearchQuery, { page, query, limit })
|
||||
.then((data) => data?.Page)
|
||||
.then((page) => {
|
||||
if (!page || page.media?.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
const response = await stub.fetch("http://anilist-do/graphql", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
operationName: "Search",
|
||||
variables: { query, page, limit },
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const data = (await response.json()) as any;
|
||||
if (!data || data.media?.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const { media: results, pageInfo } = data;
|
||||
return {
|
||||
results: results?.map((result: any) => {
|
||||
if (!result) return null;
|
||||
|
||||
const { media: results, pageInfo } = page;
|
||||
return {
|
||||
results: results?.map((result) => {
|
||||
if (!result) return null;
|
||||
|
||||
return {
|
||||
id: result.id,
|
||||
title: result.title?.userPreferred ?? result.title?.english,
|
||||
coverImage: result.coverImage,
|
||||
};
|
||||
}),
|
||||
hasNextPage: pageInfo?.hasNextPage,
|
||||
id: result.id,
|
||||
title: result.title?.userPreferred ?? result.title?.english,
|
||||
coverImage: result.coverImage,
|
||||
};
|
||||
})
|
||||
.catch((err) => {
|
||||
const response = err.response;
|
||||
if (response.status === 429) {
|
||||
console.log("429, retrying in", response.headers.get("Retry-After"));
|
||||
return sleep(Number(response.headers.get("Retry-After")!) * 1000).then(
|
||||
() => fetchSearchResultsFromAnilist(query, page, limit),
|
||||
);
|
||||
}
|
||||
|
||||
throw err;
|
||||
});
|
||||
}),
|
||||
hasNextPage: pageInfo?.hasNextPage,
|
||||
};
|
||||
}
|
||||
|
||||
type SearchResultsResponse = {
|
||||
|
||||
Reference in New Issue
Block a user