costco-grocery-list/backend/server.js
2025-11-19 23:44:29 -10:00

104 lines
2.7 KiB
JavaScript
Executable File

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const { Pool } = require('pg');
const app = express();
const port = 5000;
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());
const allowedOrigins = [
"http://localhost:3000",
"https://costco.nicosaya.com",
"https://costco.api.nicosaya.com",
];
app.use(cors({
origin: function (origin, callback) {
if (!origin) return callback(null, true);
if (allowedOrigins.includes(origin)) return callback(null, true);
if (/^http:\/\/192\.168\.\d+\.\d+/.test(origin)) return callback(null, true);
if (/^https:\/\/192\.168\.\d+\.\d+/.test(origin)) return callback(null, true);
callback(new Error("Not allowed by CORS"));
},
methods: ["GET", "POST"],
}));
app.get('/', 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.status(200).send('Grocery List API is running.');
});
app.get('/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('/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('/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('/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}`));