-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
72 lines (60 loc) · 1.88 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
const express = require("express");
const sqlite = require("sqlite3");
const path = require("path");
const PORT = process.env.PORT || 8000;
const app = express();
const db = new sqlite.Database(path.resolve(__dirname, "database.db"));
app.use(express.static(path.resolve(__dirname, 'build')));
app.use(express.json());
//create table 'contatos' if not exists
db.run(`CREATE TABLE IF NOT EXISTS contatos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
nome TEXT,
email TEXT,
telefone TEXT,
imagem_url TEXT)`
);
app.get('/api/contatos', (req, res) => {
db.all('SELECT * FROM contatos', (err, rows) => {
res.json(rows);
})
})
app.post('/api/contatos', (req, res) => {
const { nome, email, telefone, imagem_url } = req.body;
console.log(nome, email, telefone, imagem_url);
db.run(`INSERT INTO contatos (nome, email, telefone, imagem_url) VALUES (?, ?, ?, ?)`, [nome, email, telefone, imagem_url], (err) => {
if (err) {
res.status(400).json({ error: err.message });
return;
}
res.json({ id: this.lastID });
})
})
app.put('/api/contatos/:id', (req, res) => {
db.run(`UPDATE contatos SET nome = ?, email = ?, telefone = ?, imagem_url = ? WHERE id = ?`,
[req.body.nome, req.body.email, req.body.telefone, req.body.imagem_url, req.params.id, ], (err) => {
if (err) {
res.status(400).json({ error: err.message });
return;
}
res.json({ id: this.lastID });
})
})
app.delete('/api/contatos/:id', (req, res) => {
db.run(`DELETE FROM contatos WHERE id = ?`, [req.params.id], (err) => {
if (err) {
res.status(400).json({ error: err.message });
return;
}
res.json({ id: this.lastID });
})
})
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, './build', 'index.html'));
});
app.get('*', (req, res) => {
res.redirect('/');
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});