feat: save achievements cache

This commit is contained in:
Zamitto
2024-09-24 16:32:48 -03:00
parent 7e3cf0a00e
commit f3a5f90bc7
4 changed files with 90 additions and 29 deletions

View File

@@ -2,7 +2,7 @@ import type { GameShop } from "@types";
import { registerEvent } from "../register-event";
import { HydraApi } from "@main/services";
import { gameRepository } from "@main/repository";
import { gameAchievementRepository, gameRepository } from "@main/repository";
import { GameAchievement } from "@main/entity";
const getGameAchievements = async (
@@ -16,31 +16,60 @@ const getGameAchievements = async (
achievements: true,
},
});
const gameAchievements = await HydraApi.get(
const cachedAchievements = game?.achievements?.achievements;
const apiAchievement = HydraApi.get(
"/games/achievements",
{ objectId, shop },
{ needsAuth: false }
);
)
.then((achievements) => {
if (game) {
gameAchievementRepository.upsert(
{
game: { id: game.id },
achievements: JSON.stringify(achievements),
},
["game"]
);
}
return achievements;
})
.catch(() => []);
const gameAchievements = cachedAchievements
? JSON.parse(cachedAchievements)
: await apiAchievement;
const unlockedAchievements = JSON.parse(
game?.achievements?.unlockedAchievements || "[]"
) as { name: string; unlockTime: number }[];
return gameAchievements.map((achievement) => {
const unlockedAchiement = unlockedAchievements.find((localAchievement) => {
return localAchievement.name == achievement.name;
return gameAchievements
.map((achievement) => {
const unlockedAchiement = unlockedAchievements.find(
(localAchievement) => {
return localAchievement.name == achievement.name;
}
);
if (unlockedAchiement) {
return {
...achievement,
unlocked: true,
unlockTime: unlockedAchiement.unlockTime * 1000,
};
}
return { ...achievement, unlocked: false, unlockTime: null };
})
.sort((a, b) => {
if (a.unlocked && !b.unlocked) return -1;
if (!a.unlocked && b.unlocked) return 1;
return b.unlockTime - a.unlockTime;
});
if (unlockedAchiement) {
return {
...achievement,
unlocked: true,
unlockTime: unlockedAchiement.unlockTime * 1000,
};
}
return { ...achievement, unlocked: false, unlockTime: null };
});
};
registerEvent("getGameAchievements", getGameAchievements);

View File

@@ -48,7 +48,6 @@ export const saveAllLocalSteamAchivements = async () => {
);
console.log(achievementFile.filePath);
console.log(localAchievementFile);
for (const a of Object.keys(localAchievementFile)) {
// TODO: use checkUnlockedAchievements after refactoring it to be generic