-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathbookController.js
51 lines (46 loc) · 1.33 KB
/
bookController.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
var exports = module.exports = {};
// Call User model
let Book = require("../models/book");
exports.newBook = function(req, res) {
let token = getToken(req.headers);
if (token) {
console.log(req.body);
let newBook = new Book({
isbn: req.body.isbn,
title: req.body.title,
author: req.body.author,
publisher: req.body.publisher
});
newBook.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Save book failed.'});
}
res.json({success: true, msg: 'Successful created new book.'});
});
} else {
return res.status(403).send({success: false, msg: 'Unauthorized.'});
}
};
exports.booksList = function(req, res) {
let token = getToken(req.headers);
if (token) {
Book.find(function (err, books) {
if (err) return next(err);
res.json(books);
});
} else {
return res.status(403).send({success: false, msg: 'Unauthorized.'});
}
};
getToken = function (headers) {
if (headers && headers.authorization) {
let parted = headers.authorization.split(' ');
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};