First Commit
This commit is contained in:
94
server.js
Normal file
94
server.js
Normal file
@ -0,0 +1,94 @@
|
||||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const app = express();
|
||||
const PORT = 3001;
|
||||
const DATA_FILE = path.join(__dirname, 'quotes.json');
|
||||
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
|
||||
// Log every request
|
||||
app.use((req, res, next) => {
|
||||
console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
|
||||
next();
|
||||
});
|
||||
|
||||
// Helper to read data
|
||||
const readData = () => {
|
||||
try {
|
||||
if (!fs.existsSync(DATA_FILE)) {
|
||||
return [];
|
||||
}
|
||||
const data = fs.readFileSync(DATA_FILE, 'utf8');
|
||||
return JSON.parse(data);
|
||||
} catch (err) {
|
||||
console.error("Error reading data:", err);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
// Helper to write data
|
||||
const writeData = (data) => {
|
||||
try {
|
||||
fs.writeFileSync(DATA_FILE, JSON.stringify(data, null, 2), 'utf8');
|
||||
} catch (err) {
|
||||
console.error("Error writing data:", err);
|
||||
}
|
||||
};
|
||||
|
||||
// GET all quotes
|
||||
app.get('/api/quotes', (req, res) => {
|
||||
const quotes = readData();
|
||||
res.json(quotes);
|
||||
});
|
||||
|
||||
// POST a new or updated quote
|
||||
app.post('/api/quotes', (req, res) => {
|
||||
const newQuote = req.body;
|
||||
let quotes = readData();
|
||||
|
||||
const existingIndex = quotes.findIndex(q => q.id === newQuote.id);
|
||||
if (existingIndex >= 0) {
|
||||
quotes[existingIndex] = newQuote; // Update
|
||||
} else {
|
||||
quotes.push(newQuote); // Add new
|
||||
}
|
||||
|
||||
writeData(quotes);
|
||||
res.status(201).json(newQuote);
|
||||
});
|
||||
|
||||
// DELETE a quote
|
||||
app.delete('/api/quotes/:id', (req, res) => {
|
||||
const idToDelete = parseInt(req.params.id) || req.params.id; // Handle number or string
|
||||
let quotes = readData();
|
||||
|
||||
const initialLength = quotes.length;
|
||||
quotes = quotes.filter(q => q.id != idToDelete);
|
||||
|
||||
if (quotes.length < initialLength) {
|
||||
writeData(quotes);
|
||||
res.status(200).json({ message: "Quote deleted successfully" });
|
||||
} else {
|
||||
res.status(404).json({ message: "Quote not found" });
|
||||
}
|
||||
});
|
||||
|
||||
// Serve frontend static files
|
||||
app.use(express.static(path.join(__dirname, 'dist')));
|
||||
|
||||
// Fallback for SPA (React Router, etc.)
|
||||
app.get(/(.*)/, (req, res) => {
|
||||
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
|
||||
});
|
||||
|
||||
app.listen(PORT, '0.0.0.0', () => {
|
||||
console.log(`Backend server running on port ${PORT}`);
|
||||
});
|
||||
Reference in New Issue
Block a user