From dacaf347fd0b4a87cf031e1167466368311af5ef Mon Sep 17 00:00:00 2001 From: Zamitto Date: Sat, 27 Apr 2024 18:40:05 -0300 Subject: [PATCH] feat: get all games on first request --- src/main/events/catalogue/get-random-game.ts | 39 ++++++++++++++------ src/main/services/steam-250.ts | 13 +++++-- 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/src/main/events/catalogue/get-random-game.ts b/src/main/events/catalogue/get-random-game.ts index 07a827dd..d4bfd6af 100644 --- a/src/main/events/catalogue/get-random-game.ts +++ b/src/main/events/catalogue/get-random-game.ts @@ -1,27 +1,44 @@ import shuffle from "lodash/shuffle"; -import { getRandomSteam250List } from "@main/services"; +import { Steam250Game, getSteam250List } from "@main/services"; import { registerEvent } from "../register-event"; import { searchGames, searchRepacks } from "../helpers/search-games"; import { formatName } from "@main/helpers"; +let gamesList = new Array(); +let nextGameIndex = 0; + const getRandomGame = async (_event: Electron.IpcMainInvokeEvent) => { - return getRandomSteam250List().then(async (games) => { - const shuffledList = shuffle(games); + if (gamesList.length == 0) { + console.log("fetching steam 250 pages"); + gamesList = shuffle(await getSteam250List()); + } else { + console.log("getting cached list"); + } - for (const game of shuffledList) { - const repacks = searchRepacks(formatName(game.title)); + let resultObjectId = ""; - if (repacks.length) { - const results = await searchGames({ query: game.title }); + while (!resultObjectId) { + const game = gamesList[nextGameIndex]; + const repacks = searchRepacks(formatName(game.title)); - if (results.length) { - return results[0].objectID; - } + if (repacks.length) { + const results = await searchGames({ query: game.title }); + + if (results.length) { + resultObjectId = results[0].objectID; } } - }); + nextGameIndex += 1; + + if (nextGameIndex == gamesList.length - 1) { + nextGameIndex = 0; + gamesList = shuffle(gamesList); + } + } + + return resultObjectId; }; registerEvent(getRandomGame, { diff --git a/src/main/services/steam-250.ts b/src/main/services/steam-250.ts index 6447c226..079f067f 100644 --- a/src/main/services/steam-250.ts +++ b/src/main/services/steam-250.ts @@ -1,6 +1,10 @@ import axios from "axios"; import { JSDOM } from "jsdom"; -import shuffle from "lodash/shuffle"; + +export interface Steam250Game { + title: string; + objectID: string; +} export const requestSteam250 = async (path: string) => { return axios.get(`https://steam250.com${path}`).then((response) => { @@ -28,7 +32,8 @@ const steam250Paths = [ "/most_played", ]; -export const getRandomSteam250List = async () => { - const [path] = shuffle(steam250Paths); - return requestSteam250(path); +export const getSteam250List = async () => { + const gamesPromises = steam250Paths.map((path) => requestSteam250(path)); + const gamesList = (await Promise.all(gamesPromises)).flat(); + return [...new Set(gamesList)]; };