diff --git a/server/index.js b/server/index.js index 96694c3..b0f6875 100644 --- a/server/index.js +++ b/server/index.js @@ -25,6 +25,52 @@ const connectDB = async () => { pool = mysql.createPool(dbConfig); await pool.query('SELECT 1'); console.log('Connected to MariaDB'); + + // Automatically initialize tables if they don't exist + await pool.query(` + CREATE TABLE IF NOT EXISTS users ( + id VARCHAR(50) PRIMARY KEY, + height FLOAT NOT NULL, + weight FLOAT NOT NULL, + age INT NOT NULL, + gender VARCHAR(10) NOT NULL, + activityLevel VARCHAR(20) NOT NULL, + goal VARCHAR(20) NOT NULL, + bmi FLOAT NOT NULL, + tdee INT NOT NULL, + targetCalories INT NOT NULL, + targetProtein INT NOT NULL, + targetFat INT NOT NULL, + targetCarbs INT NOT NULL, + targetWater INT NOT NULL + ) + `); + await pool.query(` + CREATE TABLE IF NOT EXISTS daily_logs ( + date DATE NOT NULL, + user_id VARCHAR(50) NOT NULL, + waterIntake INT DEFAULT 0, + weight FLOAT DEFAULT NULL, + PRIMARY KEY (date, user_id), + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ) + `); + await pool.query(` + CREATE TABLE IF NOT EXISTS meals ( + id VARCHAR(50) PRIMARY KEY, + user_id VARCHAR(50) NOT NULL, + date DATE NOT NULL, + name VARCHAR(100) NOT NULL, + time VARCHAR(10) NOT NULL, + calories INT NOT NULL, + protein INT DEFAULT 0, + fat INT DEFAULT 0, + carbs INT DEFAULT 0, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ) + `); + console.log('Database tables verified/created'); + break; } catch (err) { console.error('Failed to connect to MariaDB, retrying...', err); diff --git a/test-get-profile.cjs b/test-get-profile.cjs new file mode 100644 index 0000000..c8b5679 --- /dev/null +++ b/test-get-profile.cjs @@ -0,0 +1,15 @@ +const http = require('http'); + +const req = http.request({ + hostname: 'localhost', + port: 3131, + path: '/api/profile/default_user', + method: 'GET' +}, (res) => { + let body = ''; + res.on('data', chunk => body += chunk); + res.on('end', () => console.log('Response:', res.statusCode, body)); +}); + +req.on('error', e => console.error('Error:', e)); +req.end(); diff --git a/test-len.js b/test-len.js new file mode 100644 index 0000000..f6805bf --- /dev/null +++ b/test-len.js @@ -0,0 +1,10 @@ +const errs = [ + "Table 'nutrition.users' doesn't exist", + "connect ECONNREFUSED 172.18.0.2:3306", + "connect ECONNREFUSED db:3306", + "Unknown database 'nutrition'" +]; +errs.forEach(e => { + const json = JSON.stringify({ error: e }); + console.log(Buffer.byteLength(json), json); +});