feat: initDatabase function

This commit is contained in:
Gu://em_ 2025-03-29 12:45:59 +01:00
parent 0590295e6b
commit 9e713146e1
5 changed files with 31 additions and 6 deletions

2
.gitignore vendored
View file

@ -135,6 +135,8 @@ dist
.yarn/install-state.gz .yarn/install-state.gz
.pnp.* .pnp.*
# Data
data/*
# Temporary # Temporary
tests/ tests/

View file

View file

@ -4,7 +4,7 @@ const express = require("express");
const app = express(); const app = express();
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
const { getDatabase, connectDatabase } = require('./src/database/index'); const { getDatabase, connectDatabase, initDatabase } = require('./src/database/index');
const handleError = require('./src/middleware/errors'); const handleError = require('./src/middleware/errors');
// --- Define constants --- // --- Define constants ---
@ -37,6 +37,7 @@ console.debug("Port: ", port);
// Database connection // Database connection
db = connectDatabase(config.database); db = connectDatabase(config.database);
db = initDatabase();
// --- Routing --- // --- Routing ---

View file

@ -20,5 +20,19 @@ function getDatabase() {
return db; return db;
} }
// Setups the database by creating the tables and the default objects
function initDatabase() {
if (db == null) {
throw new Error("Database is not connected");
}
module.exports = { getDatabase, connectDatabase }; db.exec("CREATE TABLE mods ( \
Name tinytext PRIMARY KEY, \
DisplayName tinytext, \
Author tinytext FOREIGN KEY,\
Versions longtext,\
OtherInfos longtext \
)");
}
module.exports = { getDatabase, connectDatabase, initDatabase };

View file

@ -9,8 +9,8 @@ class SQLiteDatabase {
async connect() { async connect() {
try { try {
this.db = new sqlite("./data/sqlite.db") this.db = new sqlite("./data/sqlite.db");
// db.pragma("journal_mode = WAL") // db.pragma("journal_mode = WAL");
console.log("Connected to SQLite"); console.log("Connected to SQLite");
} catch (err) { } catch (err) {
console.error("Error connecting to SQLite database: ", err); console.error("Error connecting to SQLite database: ", err);
@ -33,11 +33,19 @@ class SQLiteDatabase {
return this.db.prepare(sql).all(); return this.db.prepare(sql).all();
} }
} catch (err) { } catch (err) {
console.error("Error executing query: ", err); console.error("Error executing prepared query:", err);
throw err; throw err;
} }
} }
async exec(sql) {
try {
return this.db.exec(sql);
} catch (err) {
console.error("Error executing query:", err)}
}
} }
module.exports = SQLiteDatabase; module.exports = SQLiteDatabase;