// 📦 Full backend code for your Price Tracker project const express = require("express"); const axios = require("axios"); const cheerio = require("cheerio"); const mongoose = require("mongoose"); const cors = require("cors"); const app = express(); app.use(cors()); app.use(express.json()); // ⚙️ Connect to MongoDB Atlas mongoose.connect("mongodb+srv://:@cluster.mongodb.net/price-tracker", { useNewUrlParser: true, useUnifiedTopology: true, }); // 🧠 Mongoose Schemas const Product = mongoose.model("Product", new mongoose.Schema({ url: String, title: String, site: String, createdAt: { type: Date, default: Date.now } })); const Price = mongoose.model("Price", new mongoose.Schema({ productId: mongoose.Schema.Types.ObjectId, price: Number, date: { type: Date, default: Date.now } })); // 🔍 Amazon Scraper Function async function scrapeAmazon(url) { const { data } = await axios.get(url, { headers: { "User-Agent": "Mozilla/5.0" } }); const $ = cheerio.load(data); const title = $("#productTitle").text().trim(); const priceStr = $("#priceblock_ourprice").text() || $("#priceblock_dealprice").text(); const price = parseFloat(priceStr.replace(/[₹,]/g, "")); return { title, price, site: "Amazon" }; } // 🛒 Track Product Route app.post("/track-product", async (req, res) => { const { url } = req.body; if (!url) return res.json({ success: false, message: "No URL provided" }); try { const { title, price, site } = await scrapeAmazon(url); if (!price || !title) { return res.json({ success: false, message: "Failed to fetch price/title" }); } let product = await Product.findOne({ url }); if (!product) { product = await Product.create({ url, title, site }); } await Price.create({ productId: product._id, price }); res.json({ success: true, title, price, site, productId: product._id }); } catch (err) { console.error("Scraping error:", err.message); res.json({ success: false, message: "Error during scraping" }); } }); // 🪙 Gold Price Route (Optional Static Demo) app.get("/gold-price", async (req, res) => { try { // You can replace this with a real API like Metals-API const fakePrice = 5995; // INR per gram (example) res.json({ success: true, price: fakePrice, source: "Static Demo" }); } catch (err) { res.json({ success: false, message: "Failed to fetch gold price" }); } }); // 🚀 Start Server app.listen(3000, () => { console.log("Server running on http://localhost:3000"); });