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
.pnp.*
# Data
data/*
# Temporary
tests/

View file

View file

@ -4,7 +4,7 @@ const express = require("express");
const app = express();
const fs = require("fs");
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');
// --- Define constants ---
@ -37,6 +37,7 @@ console.debug("Port: ", port);
// Database connection
db = connectDatabase(config.database);
db = initDatabase();
// --- Routing ---

View file

@ -19,6 +19,20 @@ async function connectDatabase(config) {
function getDatabase() {
return db;
}
module.exports = { getDatabase, connectDatabase };
// Setups the database by creating the tables and the default objects
function initDatabase() {
if (db == null) {
throw new Error("Database is not connected");
}
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() {
try {
this.db = new sqlite("./data/sqlite.db")
// db.pragma("journal_mode = WAL")
this.db = new sqlite("./data/sqlite.db");
// db.pragma("journal_mode = WAL");
console.log("Connected to SQLite");
} catch (err) {
console.error("Error connecting to SQLite database: ", err);
@ -33,11 +33,19 @@ class SQLiteDatabase {
return this.db.prepare(sql).all();
}
} catch (err) {
console.error("Error executing query: ", err);
console.error("Error executing prepared query:", err);
throw err;
}
}
async exec(sql) {
try {
return this.db.exec(sql);
} catch (err) {
console.error("Error executing query:", err)}
}
}
module.exports = SQLiteDatabase;