2025-03-10 22:51:57 +01:00
|
|
|
const MySQLDatabase = require("./mysql");
|
|
|
|
const SQLiteDatabase = require("./sqlite");
|
|
|
|
|
2025-03-29 00:31:25 +01:00
|
|
|
let db;
|
|
|
|
|
|
|
|
async function connectDatabase(config) {
|
2025-03-10 22:51:57 +01:00
|
|
|
if (config.type === "mysql") {
|
2025-03-29 00:31:25 +01:00
|
|
|
db = new MySQLDatabase(config);
|
2025-03-10 22:51:57 +01:00
|
|
|
} else if (config.type === "sqlite") {
|
2025-03-29 00:31:25 +01:00
|
|
|
db = new SQLiteDatabase(config);
|
2025-03-10 22:51:57 +01:00
|
|
|
} else {
|
|
|
|
throw new Error("Invalid database type: ", config.type);
|
|
|
|
}
|
2025-03-29 00:31:25 +01:00
|
|
|
|
|
|
|
await db.connect();
|
|
|
|
return db;
|
|
|
|
}
|
|
|
|
|
2025-03-10 22:51:57 +01:00
|
|
|
|
2025-03-29 12:45:59 +01:00
|
|
|
// Setups the database by creating the tables and the default objects
|
2025-03-29 20:01:57 +01:00
|
|
|
async function initDatabase(config) {
|
2025-03-29 12:45:59 +01:00
|
|
|
if (db == null) {
|
|
|
|
throw new Error("Database is not connected");
|
|
|
|
}
|
|
|
|
|
2025-03-29 20:01:57 +01:00
|
|
|
// Create mods table
|
2025-03-29 12:47:10 +01:00
|
|
|
db.exec("CREATE TABLE IF NOT EXISTS mods ( \
|
2025-03-29 12:45:59 +01:00
|
|
|
Name tinytext PRIMARY KEY, \
|
|
|
|
DisplayName tinytext, \
|
2025-03-29 20:01:57 +01:00
|
|
|
Author tinytext,\
|
2025-03-29 12:45:59 +01:00
|
|
|
Versions longtext,\
|
|
|
|
OtherInfos longtext \
|
2025-03-29 20:01:57 +01:00
|
|
|
);");
|
|
|
|
|
|
|
|
// Insert example mod
|
|
|
|
if (!(await db.exists("mods", "Name", "example"))) {
|
|
|
|
console.debug("Creating default mod");
|
|
|
|
db.exec(`INSERT INTO mods (Name, DisplayName, Author, Versions, OtherInfos) \
|
|
|
|
VALUES ('example', 'Example mod', '${config.users.admin.username}', '', '');`);
|
|
|
|
}
|
2025-03-29 12:45:59 +01:00
|
|
|
}
|
|
|
|
|
2025-03-29 20:01:57 +01:00
|
|
|
|
|
|
|
function getDatabase() {
|
|
|
|
return db;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2025-03-29 12:45:59 +01:00
|
|
|
module.exports = { getDatabase, connectDatabase, initDatabase };
|