|
| 1 | + |
| 2 | +const express = require("express"); |
| 3 | +const cors = require("cors"); |
| 4 | +const path = require("path"); |
| 5 | +const sqlite3 = require("sqlite3").verbose(); |
| 6 | + |
| 7 | +const app = express(); |
| 8 | +const PORT = process.env.PORT || 3000; |
| 9 | +const dbPath = path.join(__dirname, "promos.db"); |
| 10 | +const db = new sqlite3.Database(dbPath); |
| 11 | + |
| 12 | +app.use(cors()); |
| 13 | +app.use(express.json()); |
| 14 | +app.use(express.static(path.join(__dirname, "..", "frontend"))); |
| 15 | + |
| 16 | +db.serialize(() => { |
| 17 | + db.run("CREATE TABLE IF NOT EXISTS promos (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, url TEXT, tags TEXT)"); |
| 18 | + db.run("CREATE TABLE IF NOT EXISTS clicks (promo_id INTEGER PRIMARY KEY, count INTEGER)"); |
| 19 | +}); |
| 20 | + |
| 21 | +app.post("/api/promos", (req, res) => { |
| 22 | + const { title, url, tags } = req.body; |
| 23 | + db.run("INSERT INTO promos (title, url, tags) VALUES (?, ?, ?)", [title, url, JSON.stringify(tags)], function(err) { |
| 24 | + if (err) return res.status(500).json({ error: "Insert failed" }); |
| 25 | + res.json({ id: this.lastID, title, url, tags }); |
| 26 | + }); |
| 27 | +}); |
| 28 | + |
| 29 | +app.get("/api/promos", (req, res) => { |
| 30 | + db.all("SELECT * FROM promos", [], (err, rows) => { |
| 31 | + if (err) return res.status(500).json({ error: "Read failed" }); |
| 32 | + const promos = rows.map(p => ({ ...p, tags: JSON.parse(p.tags || "[]") })); |
| 33 | + res.json(promos); |
| 34 | + }); |
| 35 | +}); |
| 36 | + |
| 37 | +app.post("/api/click", (req, res) => { |
| 38 | + const { id } = req.body; |
| 39 | + db.run("INSERT INTO clicks (promo_id, count) VALUES (?, 1) ON CONFLICT(promo_id) DO UPDATE SET count = count + 1", [id], err => { |
| 40 | + if (err) return res.status(500).json({ error: "Click error" }); |
| 41 | + res.json({ success: true }); |
| 42 | + }); |
| 43 | +}); |
| 44 | + |
| 45 | +app.get("/api/feed", (req, res) => { |
| 46 | + db.all("SELECT * FROM promos", [], (err, rows) => { |
| 47 | + if (err) return res.status(500).json({ error: "Feed error" }); |
| 48 | + const promos = rows.map(p => ({ ...p, tags: JSON.parse(p.tags || "[]") })); |
| 49 | + res.json(promos); |
| 50 | + }); |
| 51 | +}); |
| 52 | + |
| 53 | +app.listen(PORT, () => console.log(`Backend up on ${PORT}`)); |
0 commit comments