-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
55 lines (43 loc) · 1.43 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const app = express();
const PORT = 3000;
const DB_FILE = path.join(__dirname, 'db.json');
// Configurar almacenamiento de imágenes
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './uploads');
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}-${file.originalname}`);
},
});
const upload = multer({ storage });
app.use(express.json());
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.use(express.static('./'));
// Cargar productos desde db.json al iniciar
let products = [];
if (fs.existsSync(DB_FILE)) {
const data = fs.readFileSync(DB_FILE, 'utf-8');
products = JSON.parse(data);
}
// Obtener productos
app.get('/api/products', (req, res) => {
res.json(products);
});
// Agregar un nuevo producto
app.post('/api/products', upload.single('image'), (req, res) => {
const { name, price } = req.body;
const imageUrl = `/uploads/${req.file.filename}`;
const newProduct = { name, price, imageUrl };
products.push(newProduct);
// Guardar en db.json
fs.writeFileSync(DB_FILE, JSON.stringify(products, null, 2), 'utf-8');
res.status(201).json({ message: 'Producto agregado', product: newProduct });
});
app.listen(PORT, () => {
console.log(`Servidor corriendo en http://localhost:${PORT}`);
});