Spaces:
Sleeping
Sleeping
| require('dotenv').config(); | |
| const express = require('express'); | |
| const { MongoClient } = require('mongodb'); | |
| const bodyParser = require('body-parser'); | |
| const cors = require('cors'); | |
| const path = require('path'); | |
| const app = express(); | |
| app.use(bodyParser.json()); | |
| app.use(cors()); | |
| app.use(express.static(path.join(__dirname, 'public'))); | |
| const uri = process.env.MONGO_URI; | |
| const client = new MongoClient(uri); | |
| let commandsCollection; | |
| const ADMIN_API_KEY = process.env.ADMIN_API_KEY; | |
| async function connectDB() { | |
| try { | |
| await client.connect(); | |
| const db = client.db('commandsdb'); | |
| commandsCollection = db.collection('commands'); | |
| console.log('β MongoDB connected'); | |
| } catch (err) { | |
| console.error('β MongoDB connection error:', err); | |
| process.exit(1); | |
| } | |
| } | |
| connectDB(); | |
| app.post('/api/commands', async (req, res) => { | |
| try { | |
| const apiKey = req.headers['x-api-key']; | |
| if (apiKey !== ADMIN_API_KEY) { | |
| return res.status(403).json({ error: 'Unauthorized: Invalid API Key' }); | |
| } | |
| const { name, category, info } = req.body; | |
| if (!name || !category || !info) { | |
| return res.status(400).json({ error: 'All fields are required' }); | |
| } | |
| const newCommand = { name, category, info, createdAt: new Date(), updatedAt: new Date() }; | |
| const result = await commandsCollection.insertOne(newCommand); | |
| res.json({ message: 'Command added', command: { _id: result.insertedId, ...newCommand } }); | |
| } catch (err) { | |
| res.status(500).json({ error: err.message }); | |
| } | |
| }); | |
| app.get('/api/commands', async (req, res) => { | |
| try { | |
| const commands = await commandsCollection.find().sort({ createdAt: -1 }).toArray(); | |
| res.json(commands); | |
| } catch (err) { | |
| res.status(500).json({ error: err.message }); | |
| } | |
| }); | |
| app.get('/api/commands/category/:category', async (req, res) => { | |
| try { | |
| const { category } = req.params; | |
| const commands = await commandsCollection | |
| .find({ category: { $regex: new RegExp(`^${category}$`, 'i') } }) | |
| .sort({ createdAt: -1 }) | |
| .toArray(); | |
| if (!commands.length) { | |
| return res.status(404).json({ error: `No commands found under category "${category}"` }); | |
| } | |
| res.json(commands); | |
| } catch (err) { | |
| res.status(500).json({ error: err.message }); | |
| } | |
| }); | |
| app.get('/', (req, res) => { | |
| res.sendFile(path.join(__dirname, 'public', 'index.html')); | |
| }); | |
| app.get('/admin', (req, res) => { | |
| res.sendFile(path.join(__dirname, 'public', 'admin.html')); | |
| }); | |
| app.listen(7860, () => { | |
| console.log('π Active'); | |
| }); |