minecraft-web/backend/lib/db.js

89 lines
2.6 KiB
JavaScript

import mysql from "mysql2/promise";
// MariaDB 연결 풀 - 환경변수에서 로드
const dbPool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
// 캐시 데이터
let translationsCache = {};
let iconsCache = {}; // { "type:name": iconUrl } - 타입별로 구분
let gamerulesCache = {};
/**
* 번역 및 아이콘 데이터 로드 (blocks, items, entities 테이블에서)
*/
async function loadTranslations() {
try {
const [blocks] = await dbPool.query(
"SELECT name, name_ko, icon FROM blocks WHERE mod_id = 'minecraft'"
);
const [items] = await dbPool.query(
"SELECT name, name_ko, icon FROM items WHERE mod_id = 'minecraft'"
);
const [entities] = await dbPool.query(
"SELECT name, name_ko, icon FROM entities WHERE mod_id = 'minecraft'"
);
const [gamerules] = await dbPool.query(
"SELECT name, name_ko, description_ko FROM gamerules WHERE mod_id = 'minecraft'"
);
// 캐시 초기화
translationsCache = {};
iconsCache = {};
// blocks, items, entities를 캐시에 저장 (type:name 형식으로 구분)
blocks.forEach((row) => {
translationsCache[row.name] = row.name_ko;
if (row.icon) iconsCache[`block:${row.name}`] = row.icon;
});
items.forEach((row) => {
translationsCache[row.name] = row.name_ko;
if (row.icon) iconsCache[`item:${row.name}`] = row.icon;
});
entities.forEach((row) => {
translationsCache[row.name] = row.name_ko;
if (row.icon) iconsCache[`entity:${row.name}`] = row.icon;
});
// gamerules 캐시
gamerulesCache = {};
gamerules.forEach((row) => {
gamerulesCache[row.name] = {
name: row.name_ko || row.name,
description: row.description_ko || "",
};
});
const iconCount = Object.keys(iconsCache).length;
console.log(
`[DB] 번역 데이터 로드 완료: blocks ${blocks.length}개, items ${items.length}개, entities ${entities.length}개, icons ${iconCount}`
);
} catch (error) {
console.error("[DB] 번역 데이터 로드 실패:", error.message);
}
}
// 캐시 접근 함수
const getTranslations = () => translationsCache;
const getIcons = () => iconsCache;
const getGamerules = () => gamerulesCache;
const setIconCache = (key, value) => {
iconsCache[key] = value;
};
export {
dbPool,
dbPool as pool,
loadTranslations,
getTranslations,
getIcons,
getGamerules,
setIconCache,
};