-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
103 lines (85 loc) · 1.97 KB
/
index.js
File metadata and controls
103 lines (85 loc) · 1.97 KB
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
const express = require('express')
const app = express()
app.use(express.json())
var date_time = new Date();
let notes = [
{
id: "1",
name: "ABC",
number: "1234"
},
{
id: "2",
name: "DEF",
number: "5678"
},
{
id: "3",
name: "GHI",
number: "9101"
},
{
id: "4",
name: "JKL",
number: "1121"
}
]
app.get('/info', (request, response) => {
response.send(`Phonebook has info for ${notes.length} people, time is ${date_time}`)
})
const generateId = () => {
const maxId = notes.length > 0
? Math.max(...notes.map(n => Number(n.id)))
: 0
return String(maxId + 1)
}
app.post('/api/persons', (request, response) => {
const body = request.body
if (!body.number) {
return response.status(400).json({
error: 'number missing'
})
}
if (!body.name) {
return response.status(400).json({
error: 'name missing'
})
}
var result = notes.filter(x => x.name === body.name);
console.log(result)
if (result.length > 0) {
return response.status(400).json({
error: 'name must be unique'
})
}
const note = {
name: body.name,
number: body.number,
id: generateId(),
}
notes = notes.concat(note)
response.json(note)
})
app.get('/api/persons/:id', (request, response) => {
const id = request.params.id
const note = notes.find(note => note.id === id)
if (note) {
response.json(note)
} else {
response.status(404).end()
}
})
app.delete('/api/persons/:id', (request, response) => {
const id = request.params.id
notes = notes.filter(note => note.id !== id)
response.status(204).end()
})
app.get('/', (request, response) => {
response.send('<h1>Hello World!</h1>')
})
app.get('/api/persons', (request, response) => {
response.json(notes)
})
const PORT = 3001
app.listen(PORT)
console.log(`Server running on port ${PORT}`)