-
Notifications
You must be signed in to change notification settings - Fork 417
/
Copy pathBookController.js
224 lines (216 loc) · 6.17 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
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
const Book = require("../models/BookModel");
const { body,validationResult } = require("express-validator");
const { sanitizeBody } = require("express-validator");
const apiResponse = require("../helpers/apiResponse");
const auth = require("../middlewares/jwt");
var mongoose = require("mongoose");
// mongoose.set("useFindAndModify", false);
// Book Schema
function BookData(data) {
this.id = data._id;
this.title= data.title;
this.description = data.description;
this.isbn = data.isbn;
this.createdAt = data.createdAt;
}
/**
* Book List.
*
* @returns {Object}
*/
exports.bookList = [
auth,
function (req, res) {
try {
Book.find({user: req.user._id},"_id title description isbn createdAt").then((books)=>{
if(books.length > 0){
return apiResponse.successResponseWithData(res, "Operation success", books);
}else{
return apiResponse.successResponseWithData(res, "Operation success", []);
}
});
} catch (err) {
//throw error in json response with status 500.
return apiResponse.ErrorResponse(res, err);
}
}
];
/**
* Book Detail.
*
* @param {string} id
*
* @returns {Object}
*/
exports.bookDetail = [
auth,
function (req, res) {
if(!mongoose.Types.ObjectId.isValid(req.params.id)){
return apiResponse.successResponseWithData(res, "Operation success", {});
}
try {
Book.findOne({_id: req.params.id,user: req.user._id},"_id title description isbn createdAt").then((book)=>{
if(book !== null){
let bookData = new BookData(book);
return apiResponse.successResponseWithData(res, "Operation success", bookData);
}else{
return apiResponse.successResponseWithData(res, "Operation success", {});
}
});
} catch (err) {
//throw error in json response with status 500.
return apiResponse.ErrorResponse(res, err);
}
}
];
/**
* Book store.
*
* @param {string} title
* @param {string} description
* @param {string} isbn
*
* @returns {Object}
*/
exports.bookStore = [
auth,
body("title", "Title must not be empty.").isLength({ min: 1 }).trim(),
body("description", "Description must not be empty.").isLength({ min: 1 }).trim(),
body("isbn", "ISBN must not be empty").isLength({ min: 1 }).trim().custom((value,{req}) => {
return Book.findOne({isbn : value,user: req.user._id}).then(book => {
if (book) {
return Promise.reject("Book already exist with this ISBN no.");
}
});
}),
sanitizeBody("*").escape(),
(req, res) => {
try {
const errors = validationResult(req);
var book = new Book(
{ title: req.body.title,
user: req.user,
description: req.body.description,
isbn: req.body.isbn
});
if (!errors.isEmpty()) {
return apiResponse.validationErrorWithData(res, "Validation Error.", errors.array());
}
else {
//Save book.
book.save(function (err) {
if (err) { return apiResponse.ErrorResponse(res, err); }
let bookData = new BookData(book);
return apiResponse.successResponseWithData(res,"Book add Success.", bookData);
});
}
} catch (err) {
//throw error in json response with status 500.
return apiResponse.ErrorResponse(res, err);
}
}
];
/**
* Book update.
*
* @param {string} title
* @param {string} description
* @param {string} isbn
*
* @returns {Object}
*/
exports.bookUpdate = [
auth,
body("title", "Title must not be empty.").isLength({ min: 1 }).trim(),
body("description", "Description must not be empty.").isLength({ min: 1 }).trim(),
body("isbn", "ISBN must not be empty").isLength({ min: 1 }).trim().custom((value,{req}) => {
return Book.findOne({isbn : value,user: req.user._id, _id: { "$ne": req.params.id }}).then(book => {
if (book) {
return Promise.reject("Book already exist with this ISBN no.");
}
});
}),
sanitizeBody("*").escape(),
(req, res) => {
try {
const errors = validationResult(req);
var book = new Book(
{ title: req.body.title,
description: req.body.description,
isbn: req.body.isbn,
_id:req.params.id
});
if (!errors.isEmpty()) {
return apiResponse.validationErrorWithData(res, "Validation Error.", errors.array());
}
else {
if(!mongoose.Types.ObjectId.isValid(req.params.id)){
return apiResponse.validationErrorWithData(res, "Invalid Error.", "Invalid ID");
}else{
Book.findById(req.params.id, function (err, foundBook) {
if(foundBook === null){
return apiResponse.notFoundResponse(res,"Book not exists with this id");
}else{
//Check authorized user
if(foundBook.user.toString() !== req.user._id){
return apiResponse.unauthorizedResponse(res, "You are not authorized to do this operation.");
}else{
//update book.
Book.findByIdAndUpdate(req.params.id, book, {},function (err) {
if (err) {
return apiResponse.ErrorResponse(res, err);
}else{
let bookData = new BookData(book);
return apiResponse.successResponseWithData(res,"Book update Success.", bookData);
}
});
}
}
});
}
}
} catch (err) {
//throw error in json response with status 500.
return apiResponse.ErrorResponse(res, err);
}
}
];
/**
* Book Delete.
*
* @param {string} id
*
* @returns {Object}
*/
exports.bookDelete = [
auth,
function (req, res) {
if(!mongoose.Types.ObjectId.isValid(req.params.id)){
return apiResponse.validationErrorWithData(res, "Invalid Error.", "Invalid ID");
}
try {
Book.findById(req.params.id, function (err, foundBook) {
if(foundBook === null){
return apiResponse.notFoundResponse(res,"Book not exists with this id");
}else{
//Check authorized user
if(foundBook.user.toString() !== req.user._id){
return apiResponse.unauthorizedResponse(res, "You are not authorized to do this operation.");
}else{
//delete book.
Book.findByIdAndRemove(req.params.id,function (err) {
if (err) {
return apiResponse.ErrorResponse(res, err);
}else{
return apiResponse.successResponse(res,"Book delete Success.");
}
});
}
}
});
} catch (err) {
//throw error in json response with status 500.
return apiResponse.ErrorResponse(res, err);
}
}
];