-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
71 lines (60 loc) · 2 KB
/
index.js
File metadata and controls
71 lines (60 loc) · 2 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
var express = require("express");
var path = require("path");
var fs = require("fs");
var booksManager = require("./booksManager.js");
var bodyParser = require('body-parser');
var cors = require('cors');
var db = JSON.parse(fs.readFileSync(path.join(__dirname + "/db")));
var app = express();
app.use(cors());
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, CORS");
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/books", (req, res) => {
if (req.query.searchText === undefined) {
booksManager.getAllBooks().then(function (data) {
res.json(data);
}).catch(function (err) {
res.status(500).send(err);
});
} else {
booksManager.searchBooks(req.query.searchText).then(function (data) {
res.json(data);
}).catch(function (err) {
res.status(404).send(err);
});
}
});
app.delete("/books", (req, res) => {
if (!req.body || !req.body.isbn || !req.body.quantity || !(typeof req.body.quantity == 'number') ||
req.body.quantity <= 0) {
res.status(400).send("Invalid / Missing parameters: {isbn, quantity}");
return;
}
booksManager.buyBook(req.body.isbn, req.body.quantity).then(function (data) {
console.log("Book bought!");
res.status(204).end();
}).catch(function (err) {
res.status(500).send(err);
});
});
app.post("/books", (req, res) => {
if (!req.body || !req.body.isbn || !req.body.quantity ||
(!typeof req.body.quantity == 'number') || req.body.quantity <= 0) {
res.status(400).send("Invalid request");
return;
}
booksManager.addBook(req.body).then(function (data) {
console.log("Added books!");
res.status(201).end();
}).catch(function (err) {
res.status(500).send(err);
});
});
app.listen(8080);