-
Notifications
You must be signed in to change notification settings - Fork 246
/
Copy pathserver.js
executable file
·42 lines (36 loc) · 1.41 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
const express = require('express')
const cors = require('cors')
const app = express()
const port = process.env.PORT || 4001
app.use(express.json())
app.use(cors())
app.use((req, res, next) => {
if (!req.query.api_key || req.query.api_key !== 'xyz') {
res.status(403).json({ message: 'Please supply a valid api_key' })
} else {
next()
}
})
const friends = [
{ id: '1', name: 'Christopher', email: '[email protected]', age: 32, hobbies: ['coding', 'science fiction', 'sightseeing'] },
{ id: '2', name: 'Julian', email: '[email protected]', age: 28, hobbies: ['fishing', 'coding', 'death metal'] },
{ id: '3', name: 'Sofia', email: '[email protected]', age: 25, hobbies: ['hiking', 'netflix', 'coding'] },
{ id: '4', name: 'Joe', email: '[email protected]', age: 22, hobbies: ['heavy metal', 'coding', 'death metal'] },
{ id: '5', name: 'Hung', email: '[email protected]', age: 35, hobbies: ['reading', 'coding', 'bird watching'] },
{ id: '6', name: 'Trevor', email: '[email protected]', age: 24, hobbies: ['hiking', 'heavy metal', 'coding'] },
]
app.get('/friends/:id', (req, res) => {
const friend = friends.find(fr => fr.id === req.params.id)
if (!friend) {
res.status(404).json({ message: 'No such friend!' })
}
else {
res.json(friend)
}
})
app.get('/friends', (req, res) => {
res.json(friends.map(fr => ({ id: fr.id, name: fr.name })))
})
app.listen(port, () => {
console.log(`listening on ${port}`)
})