-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
132 lines (118 loc) · 2.66 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
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
const express = require('express')
const bodyParser = require('body-parser')
var cors = require('cors')
require('dotenv').config();
const app = express()
const port = process.env.PORT || 5005
let index = 8
let users = [
{
"id": 1,
"name": "Danny",
"age": 30
},
{
"id": 2,
"name": "Wesley",
"age": 62
},
{
"id": 3,
"name": "Ben",
"age": 52
},
{
"id": 4,
"name": "Matt",
"age": 45
},
{
"id": 5,
"name": "Weston",
"age": 40
},
{
"id": 6,
"name": "Amy",
"age": 35
},
{
"id": 7,
"name": "Tim",
"age": 52
},
{
"id": 8,
"name": "Mike",
"age": 36
}
]
app.use(express.static('public'))
app.use(bodyParser.json())
app.use(cors())
app.get('/', function (req, res) {
res.send('Hello, Class!')
})
app.post('/', function (req, res) {
const body = req.body
console.log(body)
res.send(body)
})
app.get('/users', function (req, res) {
res.send(users)
})
app.post('/users', function (req, res) {
const body = req.body
body.id = ++index
users.push(body)
res.send( users[users.length - 1] )
// res.send('Got a POST request at /user')
})
app.put('/users/:id', function (req, res) {
const foundIndex = users.findIndex((ele) => ele.id === req.params.id);
let results;
if (foundIndex != -1) {
users[foundIndex] = req.body;
results = users[foundIndex];
} else {
users.push(req.body);
index++;
results = users[users.length - 1];
}
res.send(results);
})
app.patch('/users/:id', function (req, res) {
const foundIndex = users.findIndex((ele) => ele.id === req.params.id);
let results;
if (foundIndex){
users[foundIndex] = req.body;
results = users[foundIndex];
} else {
results = `ID ${id} NOT FOUND`;
}
res.send(results);
})
app.delete('/users/:id', function (req, res) {
const initialLength = users.length;
let deletedUser;
users = users.filter((ele) => {
if (ele.id !== parseInt(req.params.id)){
return true;
} else {
deletedUser = ele;
return false;
}
})
if(users.length === initialLength){
res.send('Nothing Deleted');
}
res.send(deletedUser);
})
app.use(function (req, res, next) {
res.status(404).send("Sorry can't find that!")
})
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))