-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
server.js
85 lines (75 loc) · 1.58 KB
/
server.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
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
let nextId = 7;
function getNewId() {
return nextId++;
}
let friends = [
{
id: 1,
name: 'Ben',
age: 30,
email: '[email protected]',
},
{
id: 2,
name: 'Austen',
age: 32,
email: '[email protected]',
},
{
id: 3,
name: 'Ryan',
age: 35,
email: '[email protected]',
},
{
id: 4,
name: 'Sean',
age: 35,
email: '[email protected]',
},
{
id: 5,
name: 'Michelle',
age: 67,
email: '[email protected]',
},
{
id: 6,
name: 'Luis',
age: 47,
email: '[email protected]',
},
];
app.use(cors());
app.use(bodyParser.json());
app.get('/friends', (req, res) => {
res.status(200).json(friends);
});
app.post('/friends', (req, res) => {
const friend = { id: getNewId(), ...req.body };
friends = [...friends, friend];
res.status(201).json(friends);
});
app.put('/friends/:id', (req, res) => {
const { id } = req.params;
let friendIndex = friends.findIndex(friend => friend.id == id);
if (friendIndex >= 0) {
friends[friendIndex] = { ...friends[friendIndex], ...req.body };
res.status(200).json(friends);
} else {
res
.status(404)
.json({ message: `The friend with id ${id} does not exist.` });
}
});
app.delete('/friends/:id', (req, res) => {
friends = friends.filter(friend => friend.id != req.params.id);
res.status(200).json(friends);
});
app.listen(5000, () => {
console.log('server listening on port 5000');
});