From fcb6652891b71357a32eb186d2f5eee08dc5a90e Mon Sep 17 00:00:00 2001 From: kdh8219 <65698239+kdh8219@users.noreply.github.com> Date: Fri, 5 May 2023 15:58:30 +0900 Subject: [PATCH] done #4 --- src/main.ts | 5 +++-- src/wrapper/mojang-api.ts | 29 ++++++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/main.ts b/src/main.ts index 177e677..9d05380 100755 --- a/src/main.ts +++ b/src/main.ts @@ -3,6 +3,8 @@ import { config } from "dotenv"; config(); import { getCommands } from "./command/commands.js"; +import mojangAPI from "./wrapper/mojang-api.js"; +await mojangAPI.load_cache_from_firestore(); const client = new Client({ intents: [GatewayIntentBits.Guilds] }); @@ -33,11 +35,10 @@ client.on(Events.InteractionCreate, async (interaction) => { content: "There was an error while executing this command!", ephemeral: true, }); - } catch (e) { + } catch { await interaction.editReply({ content: "There was an error while executing this command!", }); - console.error(e); } } }); diff --git a/src/wrapper/mojang-api.ts b/src/wrapper/mojang-api.ts index 0b0462e..97532fa 100644 --- a/src/wrapper/mojang-api.ts +++ b/src/wrapper/mojang-api.ts @@ -1,9 +1,16 @@ import axios from "axios"; import TwoWayMap from "../utils/two-way-map.js"; +import firebase from "./firebase.js"; + +type TCacheData = { + uuid: string; + id: string; +}; export class MojangAPI { private cache: TwoWayMap = new TwoWayMap(); // uuid, id + private firestore = firebase.collection("uuidMap"); async getIdFromUUID(minecraft_uuid: string): Promise { let id = this.cache.get_by_first(minecraft_uuid); @@ -15,11 +22,16 @@ export class MojangAPI { id = request.data.name; if (!id) throw new Error("Failed to get minecraft id from api"); + const get_by_id = await this.firestore.where("id", "==", id).get(); + get_by_id.forEach((doc) => doc.ref.delete()); + this.firestore.add({ uuid: minecraft_uuid, id: id }); + this.cache.remove_by_second(id); this.cache.set_by_first(minecraft_uuid, id); + return id; } - async getUUIDFromId(minecraft_id): Promise { + async getUUIDFromId(minecraft_id: string): Promise { let uuid = this.cache.get_by_second(minecraft_id); if (uuid) return uuid; @@ -29,10 +41,25 @@ export class MojangAPI { uuid = response.data.id; if (!uuid) throw new Error("Failed to get minecraft id from api"); + const get_by_uuid = await this.firestore.where("uuid", "==", uuid).get(); + get_by_uuid.forEach((doc) => doc.ref.delete()); + this.firestore.add({ uuid: uuid, id: minecraft_id }); + this.cache.remove_by_first(uuid); this.cache.set_by_second(uuid, minecraft_id); + return uuid; } + async load_cache_from_firestore() { + const uuidMap = this.firestore; + (await uuidMap.get()).forEach((item) => { + const data = item.data() as TCacheData; + this.cache.set_by_first(data.uuid, data.id); + }); + } + get_id_from_uuid_only_cache(minecraft_uuid: string) { + return this.cache.get_by_first(minecraft_uuid); + } } const mojangAPI = new MojangAPI(); export default mojangAPI;