-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
94 lines (84 loc) · 2.51 KB
/
api.js
File metadata and controls
94 lines (84 loc) · 2.51 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
const { title } = require('errorhandler');
const express = require('express');
const apiRouter = express.Router();
const sqlite3 = require('sqlite3');
const db = new sqlite3.Database(process.env.TEST_DATABASE || './database.sqlite');
//parameter works for identifying the id for PUT and DELETE requests
apiRouter.param('/:journalId', (req, res, next, journalId) => {
db.get(`SELECT * FROM Journal WHERE Journal.id = $journalId`,
{
$journalId: journalId
}, (err, journal) => {
if (err) {
next(err)
} else if (journal) {
req.journal = journal;
next();
} else {
res.sendStatus(404);
}
});
});
apiRouter.get('/journals', (req, res) => {
db.all(`SELECT * FROM Journal`,
(err, journals) => {
if (err) {
res.sendStatus(404);
} else {
res.status(200).json({ journals })
console.log('GET WORKING')
}
});
});
apiRouter.post('/journals', (req, res, next) => {
console.log('POST WORKING')
const title = req.body.title;
const body = req.body.body;
if (!title || !body) {
return res.sendStatus(400);
}
db.run(`INSERT INTO Journal (title, body) VALUES ($title, $body)`,
{
$title: title,
$body: body
}, function (err) {
if (err) {
next(err)
} else {
res.status(201).json({ message: 'Journal Created Successfully' });
}
});
});
apiRouter.put('/journals/:journalId', (req, res, next) => {
console.log('PUT WORKING')
const title = req.body.title;
const body = req.body.body;
if (!title || !body) {
return res.sendStatus(400);
}
db.run(`UPDATE Journal SET title = $title, body = $body WHERE Journal.id = $journalId`,
{
$title: title,
$body: body,
$journalId: req.params.journalId
}, (err) => {
if (err) {
next(err)
} else {
res.status(200).json({ message: 'Journal Updated Successfully' });
}
});
});
apiRouter.delete('/journals/:journalId', (req, res) => {
console.log('DELETE WORKING')
db.run(`DELETE FROM Journal WHERE Journal.id = $journalId`, {
$journalId: req.params.journalId
}, (err)=> {
if(err) {
next(err)
} else {
res.status(204).json({ message: 'Journal Deleted Successfully' });
}
});
});
module.exports = apiRouter;