Add logger to code logic
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed

This commit is contained in:
Ethan Lane 2024-03-12 17:56:43 +00:00
parent 4a0050eb70
commit efc0186db2
8 changed files with 47 additions and 11 deletions

View file

@ -4,6 +4,7 @@ import Config from "../database/entities/app/Config";
import { glob } from "glob"; import { glob } from "glob";
import { SeriesMetadata } from "../contracts/SeriesMetadata"; import { SeriesMetadata } from "../contracts/SeriesMetadata";
import { CoreClient } from "../client/client"; import { CoreClient } from "../client/client";
import AppLogger from "../client/appLogger";
export interface CardMetadataResult { export interface CardMetadataResult {
IsSuccess: boolean; IsSuccess: boolean;
@ -21,16 +22,22 @@ export interface FindMetadataResult {
export default class CardMetadataFunction { export default class CardMetadataFunction {
public static async Execute(overrideSafeMode: boolean = false): Promise<CardMetadataResult> { public static async Execute(overrideSafeMode: boolean = false): Promise<CardMetadataResult> {
if (!overrideSafeMode && await Config.GetValue("safemode") == "true") return { AppLogger.LogInfo("Functions/CardMetadataFunction", "Executing");
if (!overrideSafeMode && await Config.GetValue("safemode") == "true") {
AppLogger.LogWarn("Functions/CardMetadataFunction", "Safe Mode is active, refusing to resync");
return {
IsSuccess: false, IsSuccess: false,
ErrorMessage: "Safe mode is on and not overridden", ErrorMessage: "Safe mode is on and not overridden",
}; };
}
const cardResult = await this.FindMetadataJSONs(); const cardResult = await this.FindMetadataJSONs();
if (cardResult.IsSuccess) { if (cardResult.IsSuccess) {
CoreClient.Cards = cardResult.Result!; CoreClient.Cards = cardResult.Result!;
console.log(`Loaded ${CoreClient.Cards.flatMap(x => x.cards).length} cards to database`); AppLogger.LogInfo("Functions/CardMetadataFunction", `Loaded ${CoreClient.Cards.flatMap(x => x.cards).length} cards to database`);
return { return {
IsSuccess: true, IsSuccess: true,
@ -38,6 +45,7 @@ export default class CardMetadataFunction {
} }
await Config.SetValue("safemode", "true"); await Config.SetValue("safemode", "true");
AppLogger.LogError("Functions/CardMetadataFunction", `Safe Mode activated due to error: ${cardResult.Error!.Message}`);
return { return {
IsSuccess: false, IsSuccess: false,
@ -52,13 +60,13 @@ export default class CardMetadataFunction {
for (const jsonPath of seriesJSONs) { for (const jsonPath of seriesJSONs) {
try { try {
console.log(`Reading file ${jsonPath}`); AppLogger.LogVerbose("Functions/CardMetadataFunction", `Reading file ${jsonPath}`);
const jsonFile = readFileSync(jsonPath); const jsonFile = readFileSync(jsonPath);
const parsedJson: SeriesMetadata[] = JSON.parse(jsonFile.toString()); const parsedJson: SeriesMetadata[] = JSON.parse(jsonFile.toString());
res.push(...parsedJson); res.push(...parsedJson);
} catch (e) { } catch (e) {
console.error(e); AppLogger.LogError("Functions/CardMetadataFunction", `Error reading file ${jsonPath}: ${e}`);
return { return {
IsSuccess: false, IsSuccess: false,

View file

@ -34,6 +34,8 @@ export default class Drop extends Command {
const randomCard = CardDropHelperMetadata.GetRandomCard(); const randomCard = CardDropHelperMetadata.GetRandomCard();
if (!randomCard) { if (!randomCard) {
AppLogger.LogWarn("Commands/Drop", "Unable to fetch card, please try again. (randomCard is null)");
await interaction.reply("Unable to fetch card, please try again."); await interaction.reply("Unable to fetch card, please try again.");
return; return;
} }

View file

@ -39,7 +39,9 @@ export default class Inventory extends Command {
embeds: [ embed.embed ], embeds: [ embed.embed ],
components: [ embed.row ], components: [ embed.row ],
}); });
} catch { } catch (e) {
AppLogger.LogError("Commands/Inventory", e as string);
await interaction.reply("No page for user found."); await interaction.reply("No page for user found.");
} }
} }

View file

@ -30,6 +30,8 @@ export default class Resync extends Command {
if (result) { if (result) {
if (await Config.GetValue("safemode") == "true") { if (await Config.GetValue("safemode") == "true") {
AppLogger.LogInfo("Commands/Resync", "Resync successful, safe mode disabled");
await Config.SetValue("safemode", "false"); await Config.SetValue("safemode", "false");
await interaction.reply("Resynced database and disabled safe mode."); await interaction.reply("Resynced database and disabled safe mode.");

View file

@ -3,6 +3,7 @@ import { CardRarity, CardRarityToColour, CardRarityToString } from "../constants
import CardRarityChances from "../constants/CardRarityChances"; import CardRarityChances from "../constants/CardRarityChances";
import { CardMetadata, DropResult } from "../contracts/SeriesMetadata"; import { CardMetadata, DropResult } from "../contracts/SeriesMetadata";
import { CoreClient } from "../client/client"; import { CoreClient } from "../client/client";
import AppLogger from "../client/appLogger";
export default class CardDropHelperMetadata { export default class CardDropHelperMetadata {
public static GetRandomCard(): DropResult | undefined { public static GetRandomCard(): DropResult | undefined {
@ -23,10 +24,14 @@ export default class CardDropHelperMetadata {
const randomCard = this.GetRandomCardByRarity(cardRarity); const randomCard = this.GetRandomCardByRarity(cardRarity);
AppLogger.LogSilly("CardDropHelperMetadata/GetRandomCard", `Random card: ${randomCard?.card.id} ${randomCard?.card.name}`);
return randomCard; return randomCard;
} }
public static GetRandomCardByRarity(rarity: CardRarity): DropResult | undefined { public static GetRandomCardByRarity(rarity: CardRarity): DropResult | undefined {
AppLogger.LogSilly("CardDropHelperMetadata/GetRandomCardByRarity", `Parameters: rarity=${rarity}`);
const allCards = CoreClient.Cards const allCards = CoreClient.Cards
.flatMap(x => x.cards) .flatMap(x => x.cards)
.filter(x => x.type == rarity); .filter(x => x.type == rarity);
@ -38,9 +43,13 @@ export default class CardDropHelperMetadata {
.find(x => x.cards.includes(card)); .find(x => x.cards.includes(card));
if (!series) { if (!series) {
AppLogger.LogWarn("CardDropHelperMetadata/GetRandomCardByRarity", `Series not found for card ${card.id}`);
return undefined; return undefined;
} }
AppLogger.LogSilly("CardDropHelperMetadata/GetRandomCardByRarity", `Random card: ${card.id} ${card.name}`);
return { return {
series: series, series: series,
card: card, card: card,
@ -48,14 +57,20 @@ export default class CardDropHelperMetadata {
} }
public static GetCardByCardNumber(cardNumber: string): CardMetadata | undefined { public static GetCardByCardNumber(cardNumber: string): CardMetadata | undefined {
AppLogger.LogSilly("CardDropHelperMetadata/GetCardByCardNumber", `Parameters: cardNumber=${cardNumber}`);
const card = CoreClient.Cards const card = CoreClient.Cards
.flatMap(x => x.cards) .flatMap(x => x.cards)
.find(x => x.id == cardNumber); .find(x => x.id == cardNumber);
AppLogger.LogSilly("CardDropHelperMetadata/GetCardByCardNumber", `Card: ${card?.id} ${card?.name}`);
return card; return card;
} }
public static GenerateDropEmbed(drop: DropResult, quantityClaimed: number, imageFileName: string): EmbedBuilder { public static GenerateDropEmbed(drop: DropResult, quantityClaimed: number, imageFileName: string): EmbedBuilder {
AppLogger.LogSilly("CardDropHelperMetadata/GenerateDropEmbed", `Parameters: drop=${drop.card.id}, quantityClaimed=${quantityClaimed}, imageFileName=${imageFileName}`);
let description = ""; let description = "";
description += `Series: ${drop.series.name}\n`; description += `Series: ${drop.series.name}\n`;
description += `Claimed: ${quantityClaimed}\n`; description += `Claimed: ${quantityClaimed}\n`;
@ -69,6 +84,8 @@ export default class CardDropHelperMetadata {
} }
public static GenerateDropButtons(drop: DropResult, claimId: string, userId: string): ActionRowBuilder<ButtonBuilder> { public static GenerateDropButtons(drop: DropResult, claimId: string, userId: string): ActionRowBuilder<ButtonBuilder> {
AppLogger.LogSilly("CardDropHelperMetadata/GenerateDropButtons", `Parameters: drop=${drop.card.id}, claimId=${claimId}, userId=${userId}`);
return new ActionRowBuilder<ButtonBuilder>() return new ActionRowBuilder<ButtonBuilder>()
.addComponents( .addComponents(
new ButtonBuilder() new ButtonBuilder()

View file

@ -4,6 +4,7 @@ import { CoreClient } from "../client/client";
import EmbedColours from "../constants/EmbedColours"; import EmbedColours from "../constants/EmbedColours";
import { CardRarity, CardRarityToString } from "../constants/CardRarity"; import { CardRarity, CardRarityToString } from "../constants/CardRarity";
import cloneDeep from "clone-deep"; import cloneDeep from "clone-deep";
import AppLogger from "../client/appLogger";
interface InventoryPage { interface InventoryPage {
id: number, id: number,
@ -21,6 +22,8 @@ interface InventoryPageCards {
export default class InventoryHelper { export default class InventoryHelper {
public static async GenerateInventoryPage(username: string, userid: string, page: number): Promise<{ embed: EmbedBuilder, row: ActionRowBuilder<ButtonBuilder> }> { public static async GenerateInventoryPage(username: string, userid: string, page: number): Promise<{ embed: EmbedBuilder, row: ActionRowBuilder<ButtonBuilder> }> {
AppLogger.LogSilly("Helpers/InventoryHelper", `Parameters: username=${username}, userid=${userid}, page=${page}`);
const cardsPerPage = 15; const cardsPerPage = 15;
const inventory = await Inventory.FetchAllByUserId(userid); const inventory = await Inventory.FetchAllByUserId(userid);
@ -73,7 +76,7 @@ export default class InventoryHelper {
const currentPage = pages[page]; const currentPage = pages[page];
if (!currentPage) { if (!currentPage) {
console.error("Unable to find page"); AppLogger.LogError("Helpers/InventoryHelper", "Unable to find page");
return Promise.reject("Unable to find page"); return Promise.reject("Unable to find page");
} }

View file

@ -1,8 +1,9 @@
import { Request, Response } from "express"; import { Request, Response } from "express";
import CardMetadataFunction from "../Functions/CardMetadataFunction"; import CardMetadataFunction from "../Functions/CardMetadataFunction";
import AppLogger from "../client/appLogger";
export default async function ReloadDB(req: Request, res: Response) { export default async function ReloadDB(req: Request, res: Response) {
console.log("Reloading Card DB..."); AppLogger.LogInfo("Hooks/ReloadDB", "Reloading Card DB...");
await CardMetadataFunction.Execute(); await CardMetadataFunction.Execute();

View file

@ -1,6 +1,7 @@
import bodyParser from "body-parser"; import bodyParser from "body-parser";
import express, { Application } from "express"; import express, { Application } from "express";
import ReloadDB from "./hooks/ReloadDB"; import ReloadDB from "./hooks/ReloadDB";
import AppLogger from "./client/appLogger";
export default class Webhooks { export default class Webhooks {
private app: Application; private app: Application;
@ -24,7 +25,7 @@ export default class Webhooks {
private setupListen() { private setupListen() {
this.app.listen(this.port, () => { this.app.listen(this.port, () => {
console.log(`API listening on port ${this.port}`); AppLogger.LogInfo("Webhooks", `API listening on port ${this.port}`);
}); });
} }
} }