-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
195 lines (148 loc) · 4.4 KB
/
Copy pathindex.js
File metadata and controls
195 lines (148 loc) · 4.4 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
//BACKEND CRUD
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors())
app.use(express.json())
//BASE DE DATOS FICTICIA
const db = [
{ID: 1, nombre: "danel", apellido: "mantilla", edad: 12},
{ID: 2, nombre: "luis", apellido: "joselu", edad: 13},
{ID: 3, nombre: "miguel", apellido: "rodolfo", edad: 14},
{ID: 4, nombre: "fernando", apellido: "ricardo", edad: 15},
{ID: 5, nombre: "yulieth", apellido: "montaner", edad: 16},
{ID: 6, nombre: "armando", apellido: "estroncio", edad: 17},
{ID: 7, nombre: "fernando", apellido: "rodrigez", edad: 18}
]
//ENDPOINT GET PARA LEER ELEMENTOS DE LA BASE DE DATOS
app.get("/",(req,res) => {
res.send({data: db})
})
//ENDPOINT GET PARA LEER ID ESPECIFICOS
app.get("/GetElement/:ID",(req, res)=>{
const {ID} = req.params;
const idNumber = Number(ID);
if(isNaN(idNumber) || idNumber <= 0){
return res.status(400).json({message: `el ID ${idNumber} no es valido`, ok: false})
}
//buscando elemento en la db
const element = db.find(item => item.ID === idNumber);
if(!element){
return res.status(404).json({message: "lo siento pa, no se encontro ningun elemento", ok: false})
}
return res.status(200).json({
ok: true,
message: "elemento encontrado con exito",
data: element
})
})
//ENDPOINT POST PARA CREAR ELEMENTOS
app.post("/addElement", (req, res) => {
try {
const { ID, nombre, apellido, edad } = req.body;
// Validación básica
if (!ID || !nombre || !apellido || edad == null) {
return res.status(400).json({
ok: false,
message: "Faltan datos obligatorios",
});
}
// Validaciones adicionales
const parsedID = Number(ID);
const parsedEdad = Number(edad);
if (isNaN(parsedID) || isNaN(parsedEdad)) {
return res.status(400).json({
ok: false,
message: "ID y Edad deben ser números",
});
}
const exists = db.some((el) => el.ID === parsedID);
if (exists) {
return res.status(409).json({
ok: false,
message: "El ID ya existe en la base de datos",
});
}
const newElement = {
ID: parsedID,
nombre,
apellido,
edad: parsedEdad,
};
db.push(newElement);
return res.status(201).json({
ok: true,
message: "Elemento agregado correctamente",
data: newElement,
});
} catch (error) {
console.error("Server error:", error);
return res.status(500).json({
ok: false,
message: "Error interno del servidor",
});
}
});
//ENDPOINT PUT PARA EDITAR ELEMENTOS
app.put("/editElement",(req, res)=>{
const {ID, nombre, apellido, edad} = req.body;
if(!ID || !nombre|| !apellido || !edad){
return res.status(400).json({
ok: false,
message: "faltan datos obligatorios"
})
}
const index = db.findIndex(item => item.ID === Number(ID));
// Si no existe el ID
if (index === -1) {
return res.status(404).json({
ok: false,
message: `No existe un elemento con el ID ${ID}`
});
}
// Reemplazar el objeto completo
db[index] = {
ID: Number(ID),
nombre,
apellido,
edad: Number(edad)
};
return res.status(200).json({
ok: true,
message: "Elemento actualizado correctamente",
data: db
});
})
//ENDPOINT DELETE PARA ELIMINAR ELEMENTOS
app.delete("/deleteElement", (req, res) => {
const ID = Number(req.body.ID);
// Validar ID
if (!req.body.ID || Number.isNaN(ID)) {
return res.status(400).json({
ok: false,
message: "Debes enviar un ID válido",
});
}
// Buscar elemento
const index = db.findIndex(item => item.ID === ID);
if (index === -1) {
return res.status(404).json({
ok: false,
message: `El elemento con ID ${ID} no existe`,
});
}
// Guardar para enviar luego
const deletedElement = db[index];
// Eliminar
db.splice(index, 1);
return res.status(200).json({
ok: true,
message: `Elemento con ID ${ID} eliminado correctamente`,
deleted: deletedElement,
data: db
});
});
const PORT = 3000;
app.listen(PORT,()=>{
console.log(`servidor escuchando en el puerto ${PORT}`)
})