-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
62 lines (51 loc) · 2.12 KB
/
Copy pathapp.js
File metadata and controls
62 lines (51 loc) · 2.12 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
/*it2022134 Exarchou Athos, mark: 9.4625*/
const express = require('express');
const app = express();
const parser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('books.sqlite');
app.use(express.static('public'));
app.use(parser.json());
db.serialize(() => { /* creates a new table in the database, in case the old database table was deleted */
db.run("CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY AUTOINCREMENT," +
"author VARCHAR(25) NOT NULL, title VARCHAR(40) NOT NULL, genre VARCHAR(20) NOT NULL, price REAL NOT NULL);");
});
app.get('/books/:keyword', function(req,res) {
const keyword = req.params.keyword;
const query = `SELECT * FROM books WHERE (title LIKE "%${keyword}%")`; /* displays the book(s) that match the given keyword */
db.all(query, (err,results) => {
/* displays the result, whether that is an error or not */
if (err) {
res.status(500);
res.send({'Error':'Internal server error'});
console.error(err);
} else {
if (results.length == 0) {
res.status(404);
res.send({'Error':'Book not found'});
console.error(err);
} else {
res.json(results);
}
}
});
});
app.post('/books', function(req, res) {
const book = req.body;
/* adds a new book to the table according to the user's input data */
const query = `INSERT INTO books (author, title, genre, price) VALUES (?, ?, ?, ?)`;
db.run(query, [book.author, book.title, book.genre, book.price], (err) => {
/* displays the result, whether that is an error or not */
if (err) {
res.status(500);
res.send({'Error':'Internal server error'});
console.error(err);
} else {
res.json({'Result':'Book added successfully!'});
}
});
});
/* opens the server at localhost:3000 */
app.listen(3000, function() {
console.log('Initiating server at: http://localhost:3000');
});