76 lines
2.5 KiB
JavaScript
76 lines
2.5 KiB
JavaScript
import express from 'express';
|
|
import { getDb } from '../models/db.js';
|
|
|
|
const router = express.Router();
|
|
|
|
router.get('/', (req, res) => {
|
|
const db = getDb();
|
|
const { user_id } = req.query;
|
|
const userId = user_id || 1;
|
|
|
|
// Return all entries, don't filter by date
|
|
const entries = db.prepare('SELECT * FROM entries WHERE user_id = ? ORDER BY created_at DESC').all(userId);
|
|
res.json(entries);
|
|
});
|
|
|
|
router.get('/recent', (req, res) => {
|
|
const db = getDb();
|
|
const { user_id, limit = 10 } = req.query;
|
|
const userId = user_id || 1;
|
|
|
|
const entries = db.prepare('SELECT DISTINCT name, description, calories, protein, carbs, fat FROM entries WHERE user_id = ? ORDER BY created_at DESC LIMIT ?').all(userId, limit);
|
|
res.json(entries);
|
|
});
|
|
|
|
router.get('/:id', (req, res) => {
|
|
const db = getDb();
|
|
const { id } = req.params;
|
|
const { user_id } = req.query;
|
|
const userId = user_id || 1;
|
|
|
|
const entry = db.prepare('SELECT * FROM entries WHERE id = ? AND user_id = ?').get(id, userId);
|
|
if (!entry) return res.status(404).json({ error: 'Entry not found' });
|
|
res.json(entry);
|
|
});
|
|
|
|
router.post('/', (req, res) => {
|
|
const db = getDb();
|
|
const { name, description, notes, calories, protein, carbs, fat, meal_time, user_id } = req.body;
|
|
const userId = user_id || 1;
|
|
|
|
const stmt = db.prepare(`
|
|
INSERT INTO entries (name, description, notes, calories, protein, carbs, fat, meal_time, user_id)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
`);
|
|
|
|
const result = stmt.run(name, description, notes, calories, protein, carbs, fat, meal_time, userId);
|
|
res.json({ id: result.lastInsertRowid, name, description, notes, calories, protein, carbs, fat, meal_time });
|
|
});
|
|
|
|
router.put('/:id', (req, res) => {
|
|
const db = getDb();
|
|
const { id } = req.params;
|
|
const { name, description, notes, calories, protein, carbs, fat, meal_time, user_id } = req.body;
|
|
const userId = user_id || 1;
|
|
|
|
const stmt = db.prepare(`
|
|
UPDATE entries SET name = ?, description = ?, notes = ?, calories = ?, protein = ?, carbs = ?, fat = ?, meal_time = ?
|
|
WHERE id = ? AND user_id = ?
|
|
`);
|
|
|
|
stmt.run(name, description, notes, calories, protein, carbs, fat, meal_time, id, userId);
|
|
res.json({ id, name, description, notes, calories, protein, carbs, fat, meal_time });
|
|
});
|
|
|
|
router.delete('/:id', (req, res) => {
|
|
const db = getDb();
|
|
const { id } = req.params;
|
|
const { user_id } = req.query;
|
|
const userId = user_id || 1;
|
|
|
|
db.prepare('DELETE FROM entries WHERE id = ? AND user_id = ?').run(id, userId);
|
|
res.json({ success: true });
|
|
});
|
|
|
|
export default router;
|