-
Notifications
You must be signed in to change notification settings - Fork 5
/
planets.js
82 lines (70 loc) · 1.84 KB
/
planets.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
const express = require('express') // get the express dependency
const bodyParser = require('body-parser') // get the body parser
let app = express() // init express
let planets = ['earth'] // new planets array
// parse application/json
app.use(bodyParser.json())
// add middleware
app.use((req, res, next) => {
console.log(req.path)
next()
})
// handle post reqs for /planets
app.post('/planets', (req, res) => {
const planet = req.body.planet
if (planet) {
planets.push(req.body.planet)
res.json(planets)
} else {
res.send('Missing required planet param')
}
})
// handle get reqs for /planets
app.get('/planets', (req, res) => {
res.json(planets)
})
// handle get reqs for /planets/:id
// handle put reqs for /planets/:id
app.put('/planets/:id', (req, res) => {
const id = req.params.id
const planet = req.body.planet
const validRequest = validateRequest(id, planets[id])
if (validRequest === true) {
planets[id] = planet
res.send(planets)
} else {
res.send(validRequest)
}
})
// handle delete reqs for /planets/:id
app.delete('/planets/:id', (req, res) => {
const id = req.params.id
const planet = planets[id]
const validRequest = validateRequest(id, planet)
if (validRequest === true) {
planets.splice(id, 1)
res.send(planets)
} else {
res.send(validRequest)
}
})
// start app on port 3000
app.listen(3000, () => {
console.log('Server running on port 3000')
})
// validator function
const validateRequest = (id, planet) => {
if (id) {
if (!isNaN(id)) {
if (planet) {
return true
} else {
return 'Planet not found'
}
} else {
return 'Id is not a number'
}
} else {
return 'Missing id param'
}
}