-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathindex.js
60 lines (45 loc) · 1.37 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
const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
app.use(bodyParser.json());
const db = new sqlite3.Database(':memory:');
db.serialize(() => {
db.run("CREATE TABLE cats (id INT, name TEXT, votes INT)");
db.run("CREATE TABLE dogs (id INT, name TEXT, votes INT)");
});
app.post('/cats', (req, res) => {
const name = req.body.name;
db.run(`INSERT INTO cats (name, votes) VALUES ('${name}', 0)`, function(err) {
if (err) {
res.status(500).send("Erro ao inserir no banco de dados");
} else {
res.status(201).json({ id: this.lastID, name, votes: 0 });
}
});
});
app.post('/dogs', (req, res) => {
});
app.post('/vote/:animalType/:id', (req, res) => {
db.run(`UPDATE ${animalType} SET votes = votes + 1 WHERE id = ${id}`);
res.status(200).send("Voto computado");
});
app.get('/cats', (req, res) => {
db.all("SELECT * FROM cats", [], (err, rows) => {
if (err) {
res.status(500).send("Erro ao consultar o banco de dados");
} else {
res.json(rows);
}
});
});
app.get('/dogs', (req, res) => {
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Ocorreu um erro!');
});
app.listen(port, () => {
console.log(`Cats and Dogs Vote app listening at http://localhost:${port}`);
});