costco-grocery-list/backend/server.js
2025-11-15 00:45:19 -08:00

74 lines
2.0 KiB
JavaScript

require('dotenv').config();
const express = require('express');
const { Pool } = require('pg');
const app = express();
const port = 5001;
const pool = new Pool({
user: process.env.DB_USER,
password: process.env.DB_PASS,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
port: 5432,
});
app.use(express.json());
// app.use(express.static('public'));
app.get('/api/suggest', async (req, res) => {
const { query } = req.query;
const { rows } = await pool.query(
'SELECT DISTINCT item_name FROM grocery_list WHERE item_name ILIKE $1 LIMIT 10',
[`%${query}%`]
);
res.json(rows.map(r => r.item_name));
});
app.post('/api/add', async (req, res) => {
const { item_name, quantity } = req.body;
const result = await pool.query(
'SELECT id, bought FROM grocery_list WHERE item_name = $1',
[item_name]
);
let listItemId;
if (result.rowCount > 0) {
listItemId = result.rows[0].id;
await pool.query(
'UPDATE grocery_list SET quantity = $1, bought = FALSE WHERE id = $2',
[quantity, listItemId]
);
res.json({ message: 'Item re-added with updated quantity.' });
} else {
const insertResult = await pool.query(
'INSERT INTO grocery_list (item_name, quantity) VALUES ($1, $2) RETURNING id',
[item_name, quantity]
);
listItemId = insertResult.rows[0].id;
res.json({ message: 'Item added to list.' });
}
await pool.query(
'INSERT INTO grocery_history (list_item_id, quantity, added_on) VALUES ($1, $2, NOW())',
[listItemId, quantity]
);
});
app.post('/api/mark-bought', async (req, res) => {
const { id } = req.body;
await pool.query('UPDATE grocery_list SET bought = TRUE WHERE id = $1', [id]);
res.json({ message: 'Item marked as bought.' });
});
app.get('/api/list', async (req, res) => {
const { rows } = await pool.query('SELECT * FROM grocery_list WHERE bought = FALSE');
res.json(rows);
});
app.listen(port, () => console.log(`Listening at http://localhost:${port}`));