From 40bf06f288915e6151290f966e00c450bb0e4412 Mon Sep 17 00:00:00 2001 From: Drew Malzahn Date: Fri, 4 Jul 2025 08:02:25 -0400 Subject: [PATCH] WIP: Add basic code for storing settings in the DB --- database.ts | 45 ++++++++++++++++++++++++++++++++++++++++++++- index.ts | 5 ++++- 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/database.ts b/database.ts index 78cad27..c74a829 100644 --- a/database.ts +++ b/database.ts @@ -1,7 +1,28 @@ -import { Sequelize } from "sequelize"; +import { Model, Sequelize, STRING } from "sequelize"; + +import "node:fs/promises"; +import { readFile } from "node:fs"; export const sql = new Sequelize("sqlite://./blitzcrank.sqlite"); +export class GuildSetting extends Model { + declare guildId: string; + declare key: string; + declare value?: string; +} + +GuildSetting.init( + { + guildId: { + type: STRING, + primaryKey: true, + }, + key: { type: STRING, primaryKey: true }, + value: { type: STRING }, + }, + { sequelize: sql }, +); + export async function initDb() { try { await sql.authenticate(); @@ -10,3 +31,25 @@ export async function initDb() { console.error("Unable to connect to the database:", error); } } + +export async function readSettingsFromFile(path: string) { + readFile(path, async (err, data) => { + try { + const json = JSON.parse(data.toString()); + const toInsert: any[] = []; + for (const [guildId, guildSettings] of json) { + for (const [key, value] of guildSettings) { + toInsert.push({ + guildId, + key, + value, + }); + } + } + GuildSetting.bulkCreate(toInsert, { updateOnDuplicate: ["value"] }); + } catch (error) { + // TODO + console.log("Could not read settings:", error); + } + }); +} diff --git a/index.ts b/index.ts index a32be9d..c6195c1 100644 --- a/index.ts +++ b/index.ts @@ -5,7 +5,7 @@ import type { SlashCommandOptionsOnlyBuilder, } from "discord.js"; -import { sql } from "./database"; +import { sql, GuildSetting, initDb } from "./database"; const BLITZCRANK_BANNER = ` ****++++++++++*+++ @@ -145,6 +145,9 @@ client.on(Events.InteractionCreate, async (interaction: Interaction) => { client.once(Events.ClientReady, async (readyClient) => { await syncCommands(); + initDb(); // TODO + GuildSetting.sync(); // TODO + for (const [_name, cmd] of commands) { await cmd?.initialize({ client: client,