-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
103 lines (91 loc) · 2.59 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
const express = require('express');
const mysql = require('./dbcon.js');
const cors = require('cors');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
const getAllQuery = 'SELECT * FROM workout';
const insertQuery = 'INSERT INTO workout (`name`, `reps`, `weight`, `units`, `date`) VALUES (?, ?, ?, ?, ?)';
const updateQuery = 'UPDATE workout SET name = ?, reps = ?, weight = ?, units = ?, date = ? WHERE id = ?';
const deleteQuery = 'DELETE FROM workout WHERE id = ?';
const dropTableQuery = 'DROP TABLE IF EXISTS workout';
const makeTableQuery = `CREATE TABLE workout(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
reps INT,
weight INT,
units VARCHAR(255),
date DATE)`;
function getAllData(res, next) {
mysql.pool.query(getAllQuery, (err, rows, fields) => {
if (err) {
next(err);
return;
}
res.json({ "rows": rows });
});
}
// get current state of the table
app.get('/', (req, res, next) => {
getAllData(res, next);
});
// insert in to the table
app.post('/', (req, res, next) => {
let { name, reps, weight, units, date } = req.body;
mysql.pool.query(insertQuery,
[name, reps, weight, units, date],
(err, result) => {
if (err) {
next(err);
return;
}
getAllData(res, next);
});
});
// delete row from the table
app.delete('/', (req, res, next) => {
let { id } = req.body;
mysql.pool.query(deleteQuery, [id], (err, result) => {
if (err) {
next(err);
return;
}
getAllData(res, next);
});
});
// update a row in the table
app.put('/', (req, res, next) => {
let { id, name, reps, weight, units, date } = req.body;
mysql.pool.query(updateQuery,
[name, reps, weight, units, date, id],
(err, result) => {
if (err) {
next(err);
return;
}
getAllData(res, next);
});
});
// empty the table
app.get('/reset-table', (req, res, next) => {
var context = {};
mysql.pool.query(dropTableQuery, (err) => {
mysql.pool.query(makeTableQuery, (err) => {
context.results = "Table reset";
res.send(context);
})
});
});
app.use((req, res) => {
res.status(404);
res.send('404-Not Found');
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500);
res.send('500-Server Error');
});
app.listen(3000, function () {
console.log('Express started on http://localhost:' + app.get('port') + '; press Ctrl-C to terminate.');
});