From 9fafa5b45d0caa10d8b2972be25fb799d87aa05d Mon Sep 17 00:00:00 2001 From: Rushil Perera Date: Mon, 28 Oct 2024 05:08:15 -0400 Subject: [PATCH] feat: improve title searching algorithm for aniwatch --- .../episodes/getByAniListId/aniwatch.ts | 48 +++++++++++++++---- src/libs/findBestMatchingTitle.ts | 6 +-- 2 files changed, 41 insertions(+), 13 deletions(-) diff --git a/src/controllers/episodes/getByAniListId/aniwatch.ts b/src/controllers/episodes/getByAniListId/aniwatch.ts index edb32a9..6dd39b6 100644 --- a/src/controllers/episodes/getByAniListId/aniwatch.ts +++ b/src/controllers/episodes/getByAniListId/aniwatch.ts @@ -122,16 +122,44 @@ async function fetchEpisodes( function getAniwatchId( animeTitle: Partial<{ english: string; userPreferred: string }>, ): Promise { - return fetch( - `https://aniwatch.up.railway.app/api/v2/hianime/search?q=${encodeURIComponent(animeTitle.english ?? animeTitle.userPreferred!)}`, - ) - .then( - (res) => - res.json() as Promise<{ - success: boolean; - data: AniwatchSearchResponse; - }>, - ) + return Promise.allSettled([ + fetch( + `https://aniwatch.up.railway.app/api/v2/hianime/search?q=${encodeURIComponent(animeTitle.english!)}`, + ), + fetch( + `https://aniwatch.up.railway.app/api/v2/hianime/search?q=${encodeURIComponent(animeTitle.userPreferred!)}`, + ), + ]) + .then((responses) => { + return responses.reduce( + async (current, res) => { + if (res.status === "rejected") { + return current; + } + + const json = (await res.value.json()) as { + success: boolean; + data: AniwatchSearchResponse; + }; + const currentValue = await current; + console.log(currentValue); + return { + success: currentValue.success || json.success, + data: { + ...currentValue.data, + animes: [ + ...currentValue.data.animes, + ...(json.data?.animes ?? []), + ], + }, + }; + }, + Promise.resolve({ + success: false, + data: { animes: [] }, + }), + ); + }) .then(({ success, data: { animes } }) => { if (!success) { return; diff --git a/src/libs/findBestMatchingTitle.ts b/src/libs/findBestMatchingTitle.ts index 1bf5526..e4dd718 100644 --- a/src/libs/findBestMatchingTitle.ts +++ b/src/libs/findBestMatchingTitle.ts @@ -22,14 +22,14 @@ type Title = { export const findBestMatchingTitle = ( title: Partial, - titles: Partial<Title>[], + titlesToSearch: Partial<Title>[], ): string | null => { const { english, userPreferred } = title; const userPreferredBestMatch = userPreferred ? findBestMatch( userPreferred, - titles + titlesToSearch .map((title) => title.userPreferred) .filter((title) => title !== undefined), ) @@ -37,7 +37,7 @@ export const findBestMatchingTitle = ( const englishBestMatch = english ? findBestMatch( english, - titles + titlesToSearch .map((title) => title.english) .filter((title) => title !== undefined), )