-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
589 lines (523 loc) · 21.1 KB
/
index.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
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
// server/index.js
const cors = require('cors');
const express = require("express");
const bodyParser = require('body-parser');
const fs = require("fs");
const url = require('url');
const mysql = require('mysql2');
const path = require("path");
require('dotenv').config();
const connectionUrl = url.parse(process.env.DATABASE_URL);
const auth = connectionUrl.auth.split(':');
const pool = mysql.createPool({
host: connectionUrl.hostname,
port: connectionUrl.port,
user: auth[0],
password: auth[1],
database: connectionUrl.pathname.substr(1),
ssl: {
rejectUnauthorized: true
}
});
const PORT = process.env.PORT || 3001;
const app = express();
app.use(bodyParser.json());
app.use(cors({
origin: 'http://localhost:5173'
}));
const isObjectEmpty = (objectName) => {
return JSON.stringify(objectName) === "{}";
};
// Users --------------------------
app.get("/api/users", (req, res) => {
var answer;
pool.getConnection(function (err, connection) {
if (err) {
console.error(err);
} else {
connection.query(`
SELECT * FROM users LEFT JOIN addresses ON users.user_id = addresses.user_id LEFT JOIN identification ON users.user_id=identification.user_id;
`, function (err, results, fields) {
if (err) {
res.status(500).send("No se pudo leer la base de datos.");
} else {
console.log(results);
answer = JSON.stringify(results, null, 2);
res.end(answer);
console.log("Query exitosa");
}
connection.release(); // <-- libera la conexión después de realizar la consulta
});
}
});
});
app.get("/api/users/:id", (req, res) => {
const id = req.params.id;
let answer;
pool.getConnection(function (err, connection) {
let query = `SELECT * FROM users WHERE user_id = ` + id + `;`;
if (err) {
console.error(err);
} else {
connection.query(
query
, function (err, results, fields) {
if (err) {
res.status(500).send("No se pudo leer la base de datos.");
} else if (!results || results.length === 0) {
res.status(400).send("No se encontró al usuario.");
console.log("Query sin resultados");
} else {
const users_results = results;
query = "SELECT * FROM addresses WHERE user_id = " + id;
connection.query(
query
, function (err, results, fields) {
if (err) {
res.status(500).send("No se pudo leer la base de datos.");
} else {
users_results[0].addresses = results;
query = "SELECT * FROM identification WHERE user_id = " + id;
connection.query(
query
, function (err, results, fields) {
if (err) {
res.status(500).send("No se pudo leer la base de datos.");
} else {
users_results[0].identifications = results;
const answer = JSON.stringify(users_results, null, 2);
res.send(answer);
console.log("Query exitosa");
}
});
}
});
}
connection.release(); // <-- libera la conexión después de realizar la consulta
});
}
});
});
app.patch("/api/users/:id", (req, res) => {
const id = req.params.id;
const curr_date = new Date().toLocaleDateString(
'es-ES',
{ day: '2-digit', month: '2-digit', year: 'numeric' }).split('/').reverse().join('-');
if (Object.keys(req.body).length === 0) {
return res.status(400).send('No se pudo interpretar la información recibida.');
}
if (!req.body.column || !req.body.data) {
res.status(400).send("Formato incorrecto.");
return;
}
const column = req.body.column;
const new_val = req.body.data;
var query = "";
var query2 = "";
if (typeof column === 'string') {
console.log("Normal Patch.");
query = "UPDATE users SET " + column + " = '" + new_val + "' WHERE user_id = " + id + ";";
query2 = "UPDATE users SET updated_at = '" + curr_date + "' WHERE user_id = " + id + ";";
}
else if (column.sector === "addresses"){
if (!column.mode || !column.name) {
res.status(400).send("Formato incorrecto.");
return;
}
console.log("Address Patch.");
if (column.mode === "single"){
if (!column.address_id) {
res.status(400).send("Formato incorrecto.");
console.log("Aborted");
return;
}
query = "UPDATE addresses SET " + column.name + " = '" + new_val + "' WHERE user_id = " + id + " AND address_id = " + column.address_id + ";";
query2 = "UPDATE addresses SET updated_at = '" + curr_date + "' WHERE user_id = " + id + " AND address_id = " + column.address_id + ";";
}
else if (column.mode === "multiple"){
query = "UPDATE addresses SET " + column.name + " = '" + new_val + "' WHERE user_id = " + id + ";";
query2 = "UPDATE addresses SET updated_at = '" + curr_date + "' WHERE user_id = " + id + ";";
}
}
else if (column.sector === "identification"){
if (!column.mode || !column.name) {
res.status(400).send("Formato incorrecto.");
return;
}
console.log("Identification Patch.");
if (column.mode === "single"){
if (!column.identification_id) {
res.status(400).send("Formato incorrecto.");
console.log("Aborted");
return;
}
query = "UPDATE identification SET " + column.name + " = '" + new_val + "' WHERE user_id = " + id + " AND identification_id = " + column.identification_id + ";";
query2 = "UPDATE identification SET updated_at = '" + curr_date + "' WHERE user_id = " + id + " AND identification_id = " + column.identification_id + ";";
}
else if (column.mode === "multiple"){
query = "UPDATE identification SET " + column.name + " = '" + new_val + "' WHERE user_id = " + id + ";";
query2 = "UPDATE identification SET updated_at = '" + curr_date + "' WHERE user_id = " + id + ";";
}
}
else {
res.status(400).send("Formato incorrecto.");
return;
}
pool.getConnection(function (err, connection) {
if (err) {
console.error(err);
res.status(500).send("No se pudo conectar a la base de datos.");
return;
}
connection.query(
query
, function (err, results, fields) {
if (err) {
console.error(err);
res.status(500).send("No se pudo leer la base de datos.");
return;
} else {
connection.query(
query2
, function (err, results, fields) {
if (err) {
console.error(err);
res.status(500).send("No se pudo leer la base de datos.");
return;
} else {
console.log("Query exitosa");
}
connection.release(); // <-- libera la conexión después de realizar la consulta
res.end("Cambio realizado.");
});
}
});
});
});
app.delete("/api/users/:id", async (req, res) => {
// Encontrar usuario y sus datos
const id = req.params.id;
const curr_date = new Date().toLocaleDateString(
'es-ES',
{ day: '2-digit', month: '2-digit', year: 'numeric' }).split('/').reverse().join('-');
pool.getConnection(function (err, connection) {
let query = `SELECT * FROM users WHERE user_id = ` + id + `;`;
if (err) {
console.error(err);
} else {
connection.query(
query
, function (err, results, fields) {
if (err) {
res.status(500).send("No se pudo leer la base de datos.");
} else if (!results || results.length === 0) {
res.status(400).send("No se encontró al usuario.");
console.log("Query sin resultados");
return;
} else if (results[0].is_client === 1) {
res.status(400).send("Usuario es cliente, no se puede nulificar.");
console.log("Query sin resultados");
return;
} else {
console.log("Usuario encontrado en users, comenzando proceso de borrado...");
query = "UPDATE users SET ";
const columns = Object.keys(results[0]);
columns.forEach(column => {
if (column != 'user_id' && column != 'created_at' && column != 'updated_at' && column != 'deleted_at'){
query += column + " = NULL, ";
}
});
query += "deleted_at = '" + curr_date + "', ";
query = query.substring(0, query.length - 2);
query += " WHERE user_id = " + id + ";";
connection.query(
query
, function (err, results, fields) {
if (err) {
console.error(err);
res.status(500).send("No se pudo leer la base de datos.");
return;
} else {
console.log("Query en users exitosa");
query = `SELECT * FROM addresses WHERE user_id = ` + id + `;`;
connection.query(
query
, function (err, results, fields) {
if (err) {
res.status(500).send("No se pudo leer la base de datos.");
} else if (!results || results.length === 0) {
console.log("Query sin resultados en address.");
query = `SELECT * FROM identification WHERE user_id = ` + id + `;`;
connection.query(
query
, function (err, results, fields) {
if (err) {
res.status(500).send("No se pudo leer la base de datos.");
} else if (!results || results.length === 0) {
console.log("Query sin resultados en identification.");
} else {
console.log("Usuario encontrado en identification, comenzando proceso de borrado...");
query = "UPDATE identification SET ";
const columns = Object.keys(results[0]);
columns.forEach(column => {
if (column != 'user_id' && column != 'identification_id' && column != 'created_at' && column != 'updated_at' && column != 'deleted_at'){
query += column + " = NULL, ";
}
});
query += "deleted_at = '" + curr_date + "', ";
query = query.substring(0, query.length - 2);
query += " WHERE user_id = " + id + ";";
connection.query(
query
, function (err, results, fields) {
if (err) {
console.error(err);
res.status(500).send("No se pudo leer la base de datos.");
} else {
console.log("Query en identification exitosa");
res.end("Usuario nullificado.");
return;
}
});
}
});
} else {
console.log("Usuario encontrado en addresses, comenzando proceso de borrado...");
query = "UPDATE addresses SET ";
const columns = Object.keys(results[0]);
columns.forEach(column => {
if (column != 'user_id' && column != 'address_id' && column != 'created_at' && column != 'updated_at' && column != 'deleted_at'){
query += column + " = NULL, ";
}
});
query += "deleted_at = '" + curr_date + "', ";
query = query.substring(0, query.length - 2);
query += " WHERE user_id = " + id + ";";
connection.query(
query
, function (err, results, fields) {
if (err) {
console.error(err);
res.status(500).send("No se pudo leer la base de datos.");
} else {
console.log("Query en addresses exitosa");
query = `SELECT * FROM identification WHERE user_id = ` + id + `;`;
connection.query(
query
, function (err, results, fields) {
if (err) {
res.status(500).send("No se pudo leer la base de datos.");
} else if (!results || results.length === 0) {
console.log("Query sin resultados en identification.");
} else {
console.log("Usuario encontrado en identification, comenzando proceso de borrado...");
query = "UPDATE identification SET ";
const columns = Object.keys(results[0]);
columns.forEach(column => {
if (column != 'user_id' && column != 'identification_id' && column != 'created_at' && column != 'updated_at' && column != 'deleted_at'){
query += column + " = NULL, ";
}
});
query += "deleted_at = '" + curr_date + "', ";
query = query.substring(0, query.length - 2);
query += " WHERE user_id = " + id + ";";
connection.query(
query
, function (err, results, fields) {
if (err) {
console.error(err);
res.status(500).send("No se pudo leer la base de datos.");
} else {
console.log("Query en identification exitosa");
res.end("Usuario nullificado.");
connection.release();
return;
}
});
}
});
res.end("Usuario nullificado.");
connection.release(); // <-- libera la conexión después de realizar la consulta
}
});
}
});
}
});
}
connection.release(); // <-- libera la conexión después de realizar la consulta
});
}
connection.release(); // <-- libera la conexión después de realizar la consulta
});
});
// ARCO Registers-----------------------------------------------------------------------------------
app.get("/api/arco_registers", (req, res) => {
var answer;
pool.getConnection(function (err, connection) {
if (err) {
console.error(err);
} else {
connection.query(`
SELECT * FROM registros_arco;
`, function (err, results, fields) {
if (err) {
res.status(500).send("No se pudo leer la base de datos.");
} else {
console.log(results);
answer = JSON.stringify(results, null, 2);
res.end(answer);
console.log("Query exitosa");
}
connection.release(); // <-- libera la conexión después de realizar la consulta
});
}
});
});
app.get("/api/arco_registers/:id", (req, res) => {
const id = req.params.id;
pool.getConnection(function (err, connection) {
if (err) {
console.error(err);
} else {
let query = `SELECT * FROM registros_arco WHERE registro_arco_id = ` + id + `;`;
connection.query(
query, function (err, results, fields) {
if (err) {
res.status(500).send("No se pudo leer la base de datos.");
} else if (!results || results.length === 0) {
console.log("Query sin resultados");
res.status(400).end("Usuario no encontrado.");
connection.release();
return;
} else {
console.log(results);
answer = JSON.stringify(results, null, 2);
res.end(answer);
console.log("Query exitosa");
}
connection.release(); // <-- libera la conexión después de realizar la consulta
});
}
});
});
app.post("/api/arco_registers", (req, res) => {
if (!req.body.user_id || !req.body.arco_type || !req.body.message) {
res.status(400).end("Formato incorrecto.");
return;
}
const user_id = req.body.user_id;
const arco_type = req.body.arco_type;
const message = req.body.message;
const curr_date = new Date().toLocaleDateString(
'es-ES',
{ day: '2-digit', month: '2-digit', year: 'numeric' }).split('/').reverse().join('-');
pool.getConnection(function (err, connection) {
if (err) {
console.error(err);
} else {
let query = `SELECT user_id FROM users WHERE user_id = ` + user_id + `;`;
connection.query(
query, function (err, results, fields) {
if (err) {
res.status(500).send("No se pudo leer la base de datos.");
} else if (!results || results.length === 0) {
console.log("Query sin resultados");
res.status(400).end("Usuario especificado no existe.");
connection.release();
return;
} else {
query = `SELECT IFNULL(MAX(registro_arco_id) + 1, 1) FROM registros_arco;`;
connection.query(
query, function (err, results, fields) {
if (err) {
res.status(500).send("No se pudo leer la base de datos.");
} else {
let last_id = results[0]['IFNULL(max(registro_arco_id) + 1, 1)'];
query = `ALTER TABLE registros_arco AUTO_INCREMENT = ` + last_id + `;`;
connection.query(
query, function (err, results, fields) {
if (err) {
res.status(500).send("No se pudo leer la base de datos.");
} else {
query = ` INSERT INTO registros_arco (user_id, arco_type, message, created_at, updated_at)`;
query += ` VALUES (` + user_id + `, '`+ arco_type + `', '` + message + `', '` + curr_date + `', '` + curr_date + `');`;
connection.query(
query, function (err, results, fields) {
if (err) {
res.status(500).send("No se pudo leer la base de datos.");
} else {
res.end("Se añadió un nuevo registro de derecho ARCO para el usuario: " + user_id + ".");
console.log("Query exitosa");
}
connection.release(); // <-- libera la conexión después de realizar la consulta
});
}
});
}
});
}
});
}
});
});
app.delete("/api/arco_registers", (req, res) => {
pool.getConnection(function (err, connection) {
if (err) {
console.error(err);
} else {
let query = `DELETE FROM
registros_arco
WHERE
registro_arco_id = (
SELECT
registro_arco_id
FROM (
SELECT
MAX(registro_arco_id) AS registro_arco_id
FROM
registros_arco
) AS temp
);`;
connection.query(
query, function (err, results, fields) {
if (err) {
res.status(500).send("No se pudo leer la base de datos.");
} else {
query = `SELECT IFNULL(MAX(registro_arco_id) + 1, 1) FROM registros_arco;`;
connection.query(
query, function (err, results, fields) {
if (err) {
res.status(500).send("No se pudo leer la base de datos.");
} else {
let last_id = results[0]['IFNULL(max(registro_arco_id) + 1, 1)'];
query = `ALTER TABLE registros_arco AUTO_INCREMENT = ` + last_id + `;`;
connection.query(
query, function (err, results, fields) {
if (err) {
res.status(500).send("No se pudo leer la base de datos.");
} else {
res.end("Se borró el ultimo registro.");
console.log("Query exitosa");
}
connection.release(); // <-- libera la conexión después de realizar la consulta
});
}
});
}
});
}
});
});
// Esto hace que NodeJS sirva los archivos resultado del build de ReactJS
// Esto va antes de nuestros endpoints pero después de la declaración de app.
app.use(express.static(path.resolve("client/dist")));
// Todas las peticiones GET que no manejamos ahora regresarán nuestra React App
// Agrega esto antes del “app.listen”
app.get("*", (req, res) => {
res.sendFile(path.resolve("client/dist", "index.html"));
});
// Listen ---------------------------|
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});