@botport/dev
Version:
Framework for our Discord bot products, published by BotPort.
79 lines (66 loc) • 2.56 kB
JavaScript
import mysql from 'mysql2/promise';
import * as dotenv from 'dotenv';
import fs from 'fs/promises';
import path from 'path';
import {fileURLToPath} from 'url';
import chalk from 'chalk';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config({path: path.join(__dirname, '..', '..', '..', '..', '..', 'dist', 'config', '.env')});
const getTimestamp = () => new Date().toLocaleTimeString();
const logger = {
info: (msg, ...args) => console.info(chalk.white(`ℹ️ [info] ${getTimestamp()} ${msg}`), ...args),
error: (msg, ...args) => console.error(chalk.red(`❌ [error] ${getTimestamp()} ${msg}`), ...args),
warn: (msg, ...args) => console.warn(chalk.yellow(`⚠️ [warn] ${getTimestamp()} ${msg}`), ...args),
debug: (msg, ...args) => {
if (process.env.DEBUG === 'true') console.log(chalk.cyan(`🕵️♂️ [debug] ${getTimestamp()} ${msg}`), ...args);
},
};
logger.debug('🔄 Initiating database pool...');
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: parseInt(process.env.DB_PORT || '3306'),
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
const db = pool;
logger.debug('✅ Database pool is ready');
async function createFromJson() {
try {
const files = await fs.readdir(__dirname);
const jsonFiles = files.filter(f => f.endsWith('.json'));
for (const file of jsonFiles) {
const full = path.join(__dirname, file);
let cfg;
try {
const fileContent = await fs.readFile(full, 'utf8');
cfg = JSON.parse(fileContent);
} catch (parseError) {
logger.warn(`Kunde inte parsa ${file}, hoppar över.`);
continue;
}
if (cfg.database && typeof cfg.database === 'object') {
for (const [tableName, sql] of Object.entries(cfg.database)) {
try {
logger.debug(`🔄 Skapar tabell ${tableName} (från ${file})`);
await db.execute(sql);
logger.info(`✅ Tabell ${tableName} är redo.`);
} catch (err) {
logger.error(`❌ Fel vid skapande av ${tableName}:`, err);
}
}
}
}
} catch (error) {
logger.error('❌ Fel vid läsning av JSON-konfigurationsfiler:', error);
}
}
async function initDatabases() {
await createFromJson();
logger.info('✅ Database initialization completed (JSON tables only)');
}
export {db, initDatabases};