forked from Deen-Bridge/dnb-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbookController.js
More file actions
221 lines (191 loc) · 6.28 KB
/
Copy pathbookController.js
File metadata and controls
221 lines (191 loc) · 6.28 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
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
import axios from "axios";
import Book from "../../models/Book.js";
import User from "../../models/User.js";
import cloudinary from "../../utils/cloudinary.js";
//cretae a book
export const createBook = async (req, res) => {
console.log("Creating book with data:", req.body);
console.log("Files received:", req.files);
try {
const { title, category, price, readCount, rating, description } = req.body;
if (!req.files || !req.files.thumbnail || !req.files.file)
return res
.status(400)
.json({ error: "Thumbnail image and book file are required" });
if (!req.user || !req.user.name) {
return res.status(401).json({
success: false,
message: "Not authorized, user not found or missing name",
});
}
// Upload thumbnail to Cloudinary
const thumbnailUpload = await new Promise((resolve, reject) => {
const stream = cloudinary.uploader.upload_stream(
{ folder: "library-books/thumbnails" },
(error, result) => {
if (error) reject(error);
else resolve(result);
}
);
stream.end(req.files.thumbnail[0].buffer);
});
// Upload book file to Cloudinary (as raw file)
const fileUpload = await new Promise((resolve, reject) => {
const stream = cloudinary.uploader.upload_stream(
{ folder: "library-books/files", resource_type: "raw" },
(error, result) => {
if (error) reject(error);
else resolve(result);
}
);
stream.end(req.files.file[0].buffer);
});
// Debug: log Cloudinary upload results
console.log("thumbnailUpload:", thumbnailUpload);
console.log("fileUpload:", fileUpload);
const book = await Book.create({
title,
author: req.user._id,
thumbnail: thumbnailUpload.secure_url,
category,
price,
description,
readCount,
rating,
image: thumbnailUpload.secure_url,
fileUrl: fileUpload.secure_url,
});
res.status(201).json({ success: true, book });
} catch (err) {
console.error("Book creation error:", err);
res.status(500).json({ success: false, error: err.message });
}
};
// get all books in the store
export const getBooks = async (req, res) => {
const books = await Book.find().populate("author").populate("reviews.user"); // populate all author fields
res.json(books);
};
// get a particular book
export const getBook = async (req, res) => {
const book = await Book.findById(req.params.id)
.populate("author")
.populate("reviews.user"); // populate all author fields
if (!book) return res.status(404).json({ error: "Book not found" });
res.json(book);
};
// get books created by the author
export const getBooksByAuthor = async (req, res) => {
try {
const { authorId } = req.params; // Get authorId from route params
if (!authorId) {
return res
.status(400)
.json({ success: false, message: "Missing author id" });
}
const books = await Book.find({ author: authorId }).populate("author");
if (!books || books.length === 0) {
return res
.status(200)
.json({ success: false, message: "No books found" });
}
res.status(200).json({ success: true, books });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
};
// delete book by id
export const deleteBook = async (req, res) => {
await Book.findByIdAndDelete(req.params.id);
res.json({ message: "Book deleted" });
};
// review books
export const addBookReview = async (req, res) => {
const { rating, comment } = req.body;
const book = await Book.findById(req.params.id);
if (!book) {
return res.status(404).json({ success: false, message: "Book not found" });
}
// Optional: Prevent duplicate reviews by the same user
const alreadyReviewed = book.reviews.find(
(r) => r.user.toString() === req.user._id.toString()
);
if (alreadyReviewed) {
return res
.status(400)
.json({ success: false, message: "Book already reviewed by this user" });
}
const review = {
user: req.user._id,
comment,
rating: Number(rating),
};
book.reviews.push(review);
// Optionally update average rating and review count
book.rating =
book.reviews.reduce((acc, item) => item.rating + acc, 0) /
book.reviews.length;
await book.save();
res
.status(201)
.json({ success: true, message: "Review added", reviews: book.reviews });
};
// recommended books for user based on their profile interest
export const fetchRecommendedBooks = async (req, res) => {
try {
const { interests } = req.body;
const recommmended = await Book.find().$where(category === interests);
res.status(200).json({ success: true, recommmended });
} catch (e) {}
};
export const streamBookPreview = async (req, res) => {
try {
const { id } = req.params;
const userId = req.user?._id;
if (!id) {
return res
.status(400)
.json({ success: false, message: "Missing book id" });
}
const book = await Book.findById(id).populate("author", "_id");
if (!book || !book.fileUrl) {
return res
.status(404)
.json({ success: false, message: "Book file not found" });
}
let hasAccess = book.price === 0;
if (userId) {
if (book.author?._id?.toString() === userId.toString()) {
hasAccess = true;
} else {
const user = await User.findById(userId).select("purchasedBooks");
if (user?.purchasedBooks?.some((entry) => entry.bookId.toString() === id)) {
hasAccess = true;
}
}
}
if (!hasAccess) {
return res
.status(403)
.json({ success: false, message: "You do not have access to this book." });
}
const fileResponse = await axios.get(book.fileUrl, {
responseType: "stream",
});
res.setHeader(
"Content-Type",
fileResponse.headers["content-type"] || "application/pdf"
);
res.setHeader(
"Content-Disposition",
`inline; filename="${encodeURIComponent(`${book.title}.pdf`)}"`
);
res.setHeader("Cache-Control", "private, max-age=0, no-cache");
fileResponse.data.pipe(res);
} catch (error) {
console.error("Error streaming book preview:", error);
res
.status(500)
.json({ success: false, message: "Unable to stream book preview" });
}
};