hub-site/backend/routes/recipes.js
2024-11-16 14:14:49 -08:00

59 lines
1.5 KiB
JavaScript

import express from "express";
import pkg from "pg";
const { Pool } = pkg; // Destructure the Pool object from the CommonJS module
const router = express.Router();
const pool = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
});
// Get all recipes
router.get("/", async (req, res) => {
try {
const result = await pool.query("SELECT * FROM recipes");
res.json(result.rows);
} catch (error) {
console.error(error);
res.status(500).json({ message: "Error fetching recipes" });
}
});
// Add a new recipe
router.post("/", async (req, res) => {
const { title, description, ingredients, tags, image_url } = req.body;
try {
const result = await pool.query(
"INSERT INTO recipes (title, description, ingredients, tags, image_url) VALUES ($1, $2, $3, $4, $5) RETURNING *",
[title, description, ingredients, tags, image_url]
);
res.status(201).json(result.rows[0]);
} catch (error) {
console.error(error);
res.status(500).json({ message: "Error adding recipe" });
}
});
// Search recipes by ingredients
router.get("/search", async (req, res) => {
const { ingredient } = req.query;
try {
const result = await pool.query(
"SELECT * FROM recipes WHERE $1 = ANY (ingredients)",
[ingredient]
);
res.json(result.rows);
} catch (error) {
console.error(error);
res.status(500).json({ message: "Error searching recipes" });
}
});
export default router;