-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
server.js
134 lines (113 loc) · 2.67 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const port = 5000;
const app = express();
const token =
'esfeyJ1c2VySWQiOiJiMDhmODZhZi0zNWRhLTQ4ZjItOGZhYi1jZWYzOTA0NUIhkufemQifQ';
let nextId = 7;
let friends = [
{
id: 1,
name: 'Rachel Green',
age: 30,
email: '[email protected]'
},
{
id: 2,
name: 'Joey Tribbiani',
age: 34,
email: '[email protected]'
},
{
id: 3,
name: 'Chandler Bing',
age: 32,
email: '[email protected]'
},
{
id: 4,
name: 'Ross Geller',
age: 32,
email: '[email protected]'
},
{
id: 5,
name: 'Monica Bing',
age: 31,
email: '[email protected]'
},
{
id: 6,
name: 'Phoebe Buffay-Hannigan',
age: 30,
email: '[email protected]'
}
];
app.use(bodyParser.json());
app.use(cors());
function authenticator(req, res, next) {
const { authorization } = req.headers;
if (authorization === token) {
next();
} else {
res.status(403).json({ error: 'User must be logged in to do that.' });
}
}
app.post('/api/login', (req, res) => {
const { username, password } = req.body;
if (username === 'BloomTech' && password === 'i<3Lambd4') {
req.loggedIn = true;
res.status(200).json({
payload: token
});
} else {
res
.status(403)
.json({ error: 'Username or Password incorrect. Please see Readme' });
}
});
app.get('/api/friends', authenticator, (req, res) => {
setTimeout(() => {
res.send(friends);
}, 1000);
});
app.get('/api/friends/:id', authenticator, (req, res) => {
const friend = friends.find(f => f.id == req.params.id);
if (friend) {
res.status(200).json(friend);
} else {
res.status(404).send({ msg: 'Friend not found' });
}
});
app.post('/api/friends', authenticator, (req, res) => {
const friend = { id: getNextId(), ...req.body };
friends = [...friends, friend];
res.send(friends);
});
app.put('/api/friends/:id', authenticator, (req, res) => {
const { id } = req.params;
const friendIndex = friends.findIndex(f => f.id == id);
if (friendIndex > -1) {
const friend = { ...friends[friendIndex], ...req.body };
friends = [
...friends.slice(0, friendIndex),
friend,
...friends.slice(friendIndex + 1)
];
res.send(friends);
} else {
res.status(404).send({ msg: 'Friend not found' });
}
});
app.delete('/api/friends/:id', authenticator, (req, res) => {
const { id } = req.params;
friends = friends.filter(f => f.id !== Number(id));
res.send(friends);
});
function getNextId() {
return nextId++;
}
app.listen(port, () => {
console.log(`server listening on port ${port}`);
});