-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
100 lines (75 loc) · 2.02 KB
/
Copy pathserver.js
File metadata and controls
100 lines (75 loc) · 2.02 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
import express from "express";
const PORT = 3000;
const host = 'localhost';
const app = express();
app.use(express.json());
const users = [
{
id: 1, nome: 'Estefano',
email: 'estefano@gmail.com',
sexo: 'Masculino',
telefone: '19912345678'
},
{
id: 2, nome: 'Nelly',
email: 'nelly@gmail.com',
sexo: 'Feminino',
telefone: '19912345679'
}
];
app.get('/users', (req, res) => {
res.status(200).json({result: users});
})
app.post('/users', (req, res) => {
const nome = req.body.nome;
const email = req.body.email;
const sexo = req.body.sexo;
const telefone = req.body.telefone;
const newUser = {
id: users.length + 1,
nome: nome,
email: email,
sexo: sexo,
telefone: telefone
}
users.push(newUser);
res.status(201).json({result: "Certo!"});
})
app.delete('/users/:id', (req, res) => {
const id = Number(req.params.id);
const index = users.findIndex(u => {u.id == id});
if(index === -1){
res.status(400).json({result: "Usuario nao encontrado!"});
}
users.splice (index, 1)
return res.status(200).json(users);
})
app.patch("/users/:id", (req, res) => {
const id = Number(req.params.id);
const userIndex = users.findIndex((user) => user.id === id);
if (userIndex === -1) {
return res.status(404).json({
result: "Usuário não encontrado."
});
}
const { nome, email, sexo, telefone } = req.body;
if (nome !== undefined) {
users[userIndex].nome = nome;
}
if (email !== undefined) {
users[userIndex].email = email;
}
if (sexo !== undefined) {
users[userIndex].sexo = sexo;
}
if (telefone !== undefined) {
users[userIndex].telefone = telefone;
}
res.status(200).json({
result: "Usuário atualizado com sucesso.",
user: users[userIndex]
});
});
app.listen(PORT, host, () => {
console.log("Servidor rodando na porta: " + PORT);
})