refactor: update script

* runs promises serially instead of running them all at once
* directly calls /new-episode route for latest episode
This commit is contained in:
2024-10-06 08:48:10 -04:00
parent 45edd284ee
commit d13bc2a64e
2 changed files with 40 additions and 38 deletions

5
src/libs/promiseQueue.ts Normal file
View File

@@ -0,0 +1,5 @@
export async function promiseQueue(queue: (() => Promise<void>)[]) {
for (const promise of queue) {
await promise();
}
}

View File

@@ -1,4 +1,5 @@
import { fetchTitleFromAnilist } from "~/libs/anilist/getTitle";
import { promiseQueue } from "~/libs/promiseQueue";
import { queueTask } from "~/libs/tasks/queueTask";
import { getDb } from "~/models/db";
import { watchStatusTable } from "~/models/schema";
@@ -13,8 +14,9 @@ if (isDevMode) {
}
await getTitleIds().then((titles) =>
Promise.all(
titles.map((title) =>
promiseQueue(
titles.map(
(title) => () =>
triggerNextEpisodeRoute(title).then((success) =>
console.log(
`Triggered next episode route for title ${title}: ${success}`,
@@ -33,7 +35,13 @@ function getTitleIds() {
}
async function triggerNextEpisodeRoute(titleId: number) {
const title = await fetchTitleFromAnilist(titleId);
let title;
try {
title = await fetchTitleFromAnilist(titleId);
} catch (error) {
console.error(`Failed to fetch title ${titleId}`, error);
return false;
}
if (!title) {
console.error(`Failed to fetch title ${titleId}`);
return false;
@@ -61,8 +69,7 @@ async function triggerNextEpisodeRoute(titleId: number) {
return false;
}
if (isDevMode) {
return fetch("http://127.0.0.1:8080/internal/new-episode", {
return fetch(`${serverUrl}/internal/new-episode`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -72,31 +79,21 @@ async function triggerNextEpisodeRoute(titleId: number) {
episodeNumber: mostRecentEpisodeNumber,
}),
})
.then((res) => res.json() as Promise<{ success: boolean }>)
.then(({ success, error }) => {
.then(
(res) =>
res.json() as Promise<{ success: boolean; message?: string }>,
)
.then((response) => {
const { success } = response;
if (!success) {
console.error(
`Failed to trigger next episode route for title ${titleId} (most recent episode: ${mostRecentEpisodeNumber})`,
error,
response,
);
}
return success;
});
} else {
return queueTask(process.env, "new-episode", {
aniListId: titleId,
episodeNumber: mostRecentEpisodeNumber,
})
.then(() => true)
.catch((error) => {
console.error(
`Failed to trigger next episode route for title ${titleId} (most recent episode: ${mostRecentEpisodeNumber})`,
error,
);
return false;
});
}
});
if (!wasSuccessful) {