Meal Tracker v1 - complete
This commit is contained in:
120
server/routes/entries.js
Normal file
120
server/routes/entries.js
Normal file
@@ -0,0 +1,120 @@
|
||||
import express from 'express';
|
||||
import multer from 'multer';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { fileURLToPath } from 'url';
|
||||
import 'dotenv/config';
|
||||
|
||||
import db from '../models/db.js';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const UPLOAD_DIR = process.env.UPLOAD_DIR || path.join(__dirname, '../../uploads');
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: (req, file, cb) => {
|
||||
cb(null, UPLOAD_DIR);
|
||||
},
|
||||
filename: (req, file, cb) => {
|
||||
const timestamp = Date.now();
|
||||
const ext = path.extname(file.originalname);
|
||||
cb(null, `${timestamp}${ext}`);
|
||||
}
|
||||
});
|
||||
|
||||
const upload = multer({
|
||||
storage,
|
||||
fileFilter: (req, file, cb) => {
|
||||
const allowedTypes = /jpeg|jpg|png|gif|webp/;
|
||||
const ext = allowedTypes.test(path.extname(file.originalname).toLowerCase());
|
||||
const mime = allowedTypes.test(file.mimetype);
|
||||
|
||||
if (ext && mime) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
cb(new Error('Only image files are allowed'), false);
|
||||
}
|
||||
},
|
||||
limits: {
|
||||
fileSize: 5 * 1024 * 1024
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/entries
|
||||
router.get('/', (req, res) => {
|
||||
try {
|
||||
const { date } = req.query;
|
||||
const entries = db.getAll(date);
|
||||
res.json(entries);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/entries/:id
|
||||
router.get('/:id', (req, res) => {
|
||||
try {
|
||||
const entry = db.getById(req.params.id);
|
||||
if (!entry) {
|
||||
return res.status(404).json({ error: 'Entry not found' });
|
||||
}
|
||||
res.json(entry);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/entries
|
||||
router.post('/', upload.single('image'), (req, res) => {
|
||||
try {
|
||||
const { name, description, notes, calories, protein, carbs, fat } = req.body;
|
||||
|
||||
if (!name) {
|
||||
return res.status(400).json({ error: 'Name is required' });
|
||||
}
|
||||
|
||||
const image_url = req.file ? `/uploads/${req.file.filename}` : null;
|
||||
|
||||
const entry = db.create({
|
||||
name,
|
||||
description,
|
||||
image_url,
|
||||
notes,
|
||||
calories: calories ? parseFloat(calories) : 0,
|
||||
protein: protein ? parseFloat(protein) : 0,
|
||||
carbs: carbs ? parseFloat(carbs) : 0,
|
||||
fat: fat ? parseFloat(fat) : 0
|
||||
});
|
||||
|
||||
res.status(201).json(entry);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/entries/:id
|
||||
router.delete('/:id', (req, res) => {
|
||||
try {
|
||||
const entry = db.getById(req.params.id);
|
||||
if (!entry) {
|
||||
return res.status(404).json({ error: 'Entry not found' });
|
||||
}
|
||||
|
||||
if (entry.image_url) {
|
||||
const imagePath = path.join(__dirname, '../../', entry.image_url);
|
||||
if (fs.existsSync(imagePath)) {
|
||||
fs.unlinkSync(imagePath);
|
||||
}
|
||||
}
|
||||
|
||||
db.remove(req.params.id);
|
||||
res.json({ message: 'Entry deleted' });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
53
server/routes/foods.js
Normal file
53
server/routes/foods.js
Normal file
@@ -0,0 +1,53 @@
|
||||
import express from 'express';
|
||||
const router = express.Router();
|
||||
|
||||
const OPENFOODFACTS_API = 'https://world.openfoodfacts.org/cgi/search.pl';
|
||||
|
||||
// GET /api/foods/search?q=
|
||||
router.get('/search', async (req, res) => {
|
||||
try {
|
||||
const { q } = req.query;
|
||||
|
||||
if (!q || q.trim().length < 2) {
|
||||
return res.status(400).json({ error: 'Search query must be at least 2 characters' });
|
||||
}
|
||||
|
||||
const params = new URLSearchParams({
|
||||
search_terms: q,
|
||||
search_simple: 1,
|
||||
action: 'process',
|
||||
json: 1,
|
||||
page_size: 20,
|
||||
fields: 'product_name,brands,nutriments,serving_size'
|
||||
});
|
||||
|
||||
const response = await fetch(`${OPENFOODFACTS_API}?${params}`, {
|
||||
headers: {
|
||||
'User-Agent': 'MealTracker/1.0'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`OpenFoodFacts API error: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
const foods = (data.products || []).map(product => ({
|
||||
name: product.product_name || 'Unknown',
|
||||
brand: product.brands || null,
|
||||
calories: product.nutriments?.['energy-kcal_100g'] ?? product.nutriments?.['energy-kcal'] ?? 0,
|
||||
protein: product.nutriments?.proteins_100g ?? product.nutriments?.proteins ?? 0,
|
||||
carbs: product.nutriments?.carbohydrates_100g ?? product.nutriments?.carbohydrates ?? 0,
|
||||
fat: product.nutriments?.fat_100g ?? product.nutriments?.fat ?? 0,
|
||||
serving_size: product.serving_size || '100g'
|
||||
})).filter(f => f.name !== 'Unknown');
|
||||
|
||||
res.json(foods);
|
||||
} catch (err) {
|
||||
console.error('Food search error:', err);
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
26
server/routes/summary.js
Normal file
26
server/routes/summary.js
Normal file
@@ -0,0 +1,26 @@
|
||||
import express from 'express';
|
||||
import db from '../models/db.js';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// GET /api/summary/daily?date=YYYY-MM-DD
|
||||
router.get('/daily', (req, res) => {
|
||||
try {
|
||||
const { date } = req.query;
|
||||
|
||||
if (!date) {
|
||||
return res.status(400).json({ error: 'Date parameter is required (YYYY-MM-DD)' });
|
||||
}
|
||||
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
|
||||
return res.status(400).json({ error: 'Invalid date format. Use YYYY-MM-DD' });
|
||||
}
|
||||
|
||||
const summary = db.getDailyTotals(date);
|
||||
res.json(summary);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
Reference in New Issue
Block a user