forked from bloominstituteoftechnology/back-end-project-week
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
117 lines (102 loc) · 2.91 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
const express = require('express');
const helmet = require('helmet');
const knex = require('knex');
const knexConfig = require('./knexfile.js');
const db = knex(knexConfig.development);
const cors = require('cors');
const corsOptions = {
origin: '*',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
const server = express();
server.use(express.json());
server.use(helmet());
server.use(cors(corsOptions));
const port = 8000;
server.listen(port, () => console.log(`API running on port ${port}`));
// sanity check
server.get('/', (request, response) => {
response.send('Server initialized.');
});
// POST request
server.post('/api/notes', (request, response) => {
const title = request.body.title;
const content = request.body.content;
const newNote = { title, content };
db
.insert(newNote)
.into('notes')
.then(ids => {
return response
.status(201)
.json(ids[0]);
})
.catch(() => {
return response
.status(500)
.json({ Error: "There was an error while saving the note" })
});
});
server.get('/api/notes', (request, response) => {
db('notes')
.then(notes => {
return response
.status(200)
.json(notes);
})
.catch(() => {
return response
.status(500)
.json({ Error: "Could not find list of notes." })
});
});
server.get('/api/notes/:id', (request, response) => {
const id = request.params.id;
db('notes')
.where({ id })
.then(note => {
return response
.status(200)
.json(note);
})
.catch(() => {
return response
.status(500)
.json({ Error: "Note info could not be retrieved." })
});
});
server.put('/api/notes/:id', (request, response) => {
const id = request.params.id;
const title = request.body.title;
const content = request.body.content;
const updatedNote = { title, content };
db('notes')
.where('id', '=', id)
.update(updatedNote)
.then(note => {
return response
.status(200)
.json(note);
})
.catch(() => {
return response
.status(500)
.json({ Error: "The note info could not be modified" })
});
});
server.delete('/api/notes/:id', (request, response) => {
const id = request.params.id;
db('notes')
.where({ id })
.del()
.then(removedNote => {
return response
.status(200)
.json(removedNote);
})
.catch(() => {
return response
.status(500)
.json({ Error: "The note could not be removed" })
});
});