From c7d71036d7fcf8ba1792c69706a1e29bae44973a Mon Sep 17 00:00:00 2001 From: RHM Date: Tue, 9 Sep 2025 15:26:02 +0200 Subject: [PATCH] update database layout --- backend/package.json | 2 +- backend/src/db.js | 45 +++++++++++++++++++++++++++++++++++++------- backend/src/index.js | 5 +++-- 3 files changed, 42 insertions(+), 10 deletions(-) diff --git a/backend/package.json b/backend/package.json index 7033287..30c08d6 100644 --- a/backend/package.json +++ b/backend/package.json @@ -4,7 +4,7 @@ "description": "", "license": "MIT", "author": "", - "type": "commonjs", + "type": "module", "main": "src/index.js", "scripts": { "start": "node src/index.js" diff --git a/backend/src/db.js b/backend/src/db.js index 8c2144e..430ff8c 100644 --- a/backend/src/db.js +++ b/backend/src/db.js @@ -1,15 +1,15 @@ // copied from one of my older projects -const mysql = require('mysql2/promise'); +import { createPool } from 'mysql2/promise'; function getEnvVar(name) { const value = process.env[name]; - if (value === null) { + if (value == null) { throw new Error(`Environment variable ${name} is not defined`); } return value; } -const pool = mysql.createPool({ +const pool = createPool({ host: getEnvVar('MYSQL_HOST'), user: getEnvVar('MYSQL_USER'), password: getEnvVar('MYSQL_PASSWORD'), @@ -18,13 +18,44 @@ const pool = mysql.createPool({ const migrations = [ { - name: "init_dart_table", + name: "init", up: async (conn) => { await conn.query(` - CREATE TABLE dart ( - id INT PRIMARY KEY AUTO_INCREMENT + CREATE TABLE IF NOT EXISTS users ( + id INT PRIMARY KEY AUTO_INCREMENT, + name VARCHAR(255) NOT NULL ) `); + + await conn.query(` + CREATE TABLE IF NOT EXISTS games ( + id INT PRIMARY KEY AUTO_INCREMENT, + name VARCHAR(255) NOT NULL UNIQUE + ) + `); + + await conn.query(` + CREATE TABLE IF NOT EXISTS scores ( + id INT PRIMARY KEY AUTO_INCREMENT, + user_id INT NOT NULL, + game_id INT NOT NULL, + score INT NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id), + FOREIGN KEY (game_id) REFERENCES games(id), + UNIQUE(user_id, game_id) + ) + `); + + await conn.query(` + CREATE INDEX IF NOT EXISTS idx_scores_game_score + ON scores(game_id, score DESC) + `); + + await pool.query( + `INSERT INTO games (name) VALUES (?) ON DUPLICATE KEY UPDATE id=id`, + ['darts'] + ); } } ]; @@ -64,7 +95,7 @@ async function initDB() { } } -module.exports = { +export { pool, initDB }; \ No newline at end of file diff --git a/backend/src/index.js b/backend/src/index.js index 4b32d90..f073bc6 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -1,4 +1,5 @@ -require('dotenv').config() -const db = require('./db'); +import dotenv from 'dotenv'; +dotenv.config(); +const db = await import('./db.js'); db.initDB(); \ No newline at end of file