-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
84 lines (75 loc) · 1.94 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
const express = require('express');
const cors = require('cors');
const port = 3333;
const server = express();
server.use(express.json());
server.use(cors());
const sendUserError = (msg, res) => {
res.status(422);
res.json({ Error: msg });
return;
};
let smurfs = [
{
name: 'Brainey',
age: 200,
height: '5cm',
}
];
server.get('/smurfs', (req, res) => {
res.json(smurfs);
});
let smurfId = 0;
server.post('/smurfs', (req, res) => {
const { name, age, height } = req.body;
const newSmurf = { name, age, height, id: smurfId };
if (!name || !age || !height) {
return sendUserError(
'Ya gone did smurfed! Name/Age/Height are all required to create a smurf in the smurf DB.',
res
);
}
const findSmurfByName = smurf => {
return smurf.name === name;
};
if (smurfs.find(findSmurfByName)) {
return sendUserError(
`Ya gone did smurfed! ${name} already exists in the smurf DB.`,
res
);
}
smurfs.push(newSmurf);
smurfId++;
res.json(smurfs);
});
server.put('/smurfs/:id', (req, res) => {
const { id } = req.params;
const { name, age, height } = req.body;
const findSmurfById = smurf => {
return smurf.id == id;
};
const foundSmurf = smurfs.find(findSmurfById);
if (!foundSmurf) {
return sendUserError('No Smurf found by that ID', res);
} else {
if (name) foundSmurf.name = name;
if (age) foundSmurf.age = age;
if (height) foundSmurf.height = height;
res.json(smurfs);
}
});
server.delete('/smurfs/:id', (req, res) => {
const { id } = req.params;
const foundSmurf = smurfs.find(smurf => smurf.id == id);
if (foundSmurf) {
const SmurfRemoved = { ...foundSmurf };
smurfs = smurfs.filter(smurf => smurf.id != id);
res.status(200).json(smurfs);
} else {
sendUserError('No smurf by that ID exists in the smurf DB', res);
}
});
server.listen(port, err => {
if (err) console.log(err);
console.log(`server is listening on port ${port}`);
});