Skip to content

Commit 8c5e7c5

Browse files
committed
refactor: restructure server.js to improve API integration and error handling
1 parent 1c1f704 commit 8c5e7c5

File tree

1 file changed

+160
-11
lines changed
  • 01-contenedores/lemoncode-challenge/node-stack/frontend

1 file changed

+160
-11
lines changed
Lines changed: 160 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,170 @@
1-
//Módulos
2-
const express = require('express'),
3-
app = express();
1+
require('dotenv').config();
42

5-
const LOCAL = 'http://localhost:5000/api/topics';
3+
const express = require('express');
4+
const axios = require('axios');
5+
const path = require('path');
66

7+
const app = express();
8+
9+
// ============================================
10+
// CONFIGURACIÓN
11+
// ============================================
12+
const PORT = process.env.PORT || 3000;
13+
const API_URL = process.env.API_URL || 'http://localhost:5001';
14+
const HOST = process.env.HOST || '0.0.0.0';
15+
16+
// ============================================
17+
// MIDDLEWARES
18+
// ============================================
719
app.set('view engine', 'ejs');
20+
app.set('views', path.join(__dirname, 'views'));
21+
app.use(express.static(path.join(__dirname, 'public')));
22+
app.use(express.json());
23+
app.use(express.urlencoded({ extended: true }));
24+
25+
// ============================================
26+
// UTILIDADES - LLAMADAS A LA API
27+
// ============================================
28+
async function getTopics() {
29+
try {
30+
const response = await axios.get(`${API_URL}/api/topics`);
31+
return response.data;
32+
} catch (error) {
33+
console.error('Error al obtener topics:', error.message);
34+
return [];
35+
}
36+
}
37+
38+
async function getTopic(id) {
39+
try {
40+
const response = await axios.get(`${API_URL}/api/topics/${id}`);
41+
return response.data;
42+
} catch (error) {
43+
console.error('Error al obtener topic:', error.message);
44+
return null;
45+
}
46+
}
47+
48+
async function createTopic(data) {
49+
try {
50+
const response = await axios.post(`${API_URL}/api/topics`, data);
51+
return response.data;
52+
} catch (error) {
53+
console.error('Error al crear topic:', error.message);
54+
throw error;
55+
}
56+
}
57+
58+
async function updateTopic(id, data) {
59+
try {
60+
const response = await axios.put(`${API_URL}/api/topics/${id}`, data);
61+
return response.data;
62+
} catch (error) {
63+
console.error('Error al actualizar topic:', error.message);
64+
throw error;
65+
}
66+
}
867

9-
app.get('/', async (_, res) => {
68+
async function deleteTopic(id) {
69+
try {
70+
await axios.delete(`${API_URL}/api/topics/${id}`);
71+
return true;
72+
} catch (error) {
73+
console.error('Error al eliminar topic:', error.message);
74+
throw error;
75+
}
76+
}
77+
78+
// ============================================
79+
// RUTAS - VISTAS
80+
// ============================================
81+
82+
// Página principal - Lista de topics
83+
app.get('/', async (req, res) => {
84+
try {
85+
const topics = await getTopics();
86+
res.render('index', { topics, message: req.query.message });
87+
} catch (error) {
88+
res.status(500).render('error', { error: 'Error al cargar los topics' });
89+
}
90+
});
91+
92+
// Página para crear nuevo topic
93+
app.get('/create', (req, res) => {
94+
res.render('create');
95+
});
1096

11-
//Recuperar topics de la API
12-
const response = await fetch(process.env.API_URI || LOCAL);
13-
const topics = await response.json();
97+
// Procesar formulario de creación
98+
app.post('/create', async (req, res) => {
99+
try {
100+
const { name, description } = req.body;
101+
102+
if (!name || !description) {
103+
return res.render('create', { error: 'El nombre y descripción son obligatorios' });
104+
}
14105

106+
await createTopic({ name, description });
107+
res.redirect('/?message=Topic creado exitosamente');
108+
} catch (error) {
109+
res.render('create', { error: 'Error al crear el topic' });
110+
}
111+
});
112+
113+
// Página para editar topic
114+
app.get('/edit/:id', async (req, res) => {
115+
try {
116+
const topic = await getTopic(req.params.id);
117+
if (!topic) {
118+
return res.status(404).render('error', { error: 'Topic no encontrado' });
119+
}
120+
res.render('edit', { topic });
121+
} catch (error) {
122+
res.status(500).render('error', { error: 'Error al cargar el topic' });
123+
}
124+
});
125+
126+
// Procesar formulario de edición
127+
app.post('/edit/:id', async (req, res) => {
128+
try {\n const { name, description } = req.body;
129+
130+
if (!name || !description) {
131+
const topic = await getTopic(req.params.id);
132+
return res.render('edit', { topic, error: 'El nombre y descripción son obligatorios' });
133+
}
134+
135+
await updateTopic(req.params.id, { name, description });
136+
res.redirect('/?message=Topic actualizado exitosamente');
137+
} catch (error) {
138+
res.status(500).render('error', { error: 'Error al actualizar el topic' });
139+
}
140+
});
141+
142+
// Eliminar topic
143+
app.post('/delete/:id', async (req, res) => {
144+
try {
145+
await deleteTopic(req.params.id);
146+
res.redirect('/?message=Topic eliminado exitosamente');
147+
} catch (error) {
148+
res.status(500).render('error', { error: 'Error al eliminar el topic' });
149+
}
150+
});
151+
152+
// ============================================
153+
// MANEJO DE ERRORES
154+
// ============================================
155+
app.use((err, req, res, next) => {
156+
console.error('Error:', err);
157+
res.status(500).render('error', { error: 'Algo salió mal' });
158+
});
15159

16-
res.render('index', { topics });
160+
app.use((req, res) => {
161+
res.status(404).render('error', { error: 'Página no encontrada' });
17162
});
18163

19-
app.listen(3000, () => {
20-
console.log(`Server running on port 3000 with ${process.env.API_URI || LOCAL}`);
164+
// ============================================
165+
// INICIO DEL SERVIDOR
166+
// ============================================
167+
app.listen(PORT, HOST, () => {
168+
console.log(`🌐 Frontend ejecutándose en http://${HOST}:${PORT}`);
169+
console.log(`📡 Conectando a API en ${API_URL}`);
21170
});

0 commit comments

Comments
 (0)