All files / features/books book.controller.js

31.11% Statements 28/90
25% Branches 9/36
9.09% Functions 1/11
31.11% Lines 28/90

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 2141x 1x         1x         1x                 1x 1x 1x   1x       1x       1x       1x                                             1x     1x       1x       1x 1x 1x     1x 1x   1x   1x 1x               1x                     1x                               1x                       1x                                                                                     1x                                                                 1x                  
const Book = require('./book.model')
const { StatusCodes } = require('http-status-codes')
const {
  NotFoundError,
  BadRequestError,
  UnauthenticatedError,
} = require('../../errors')
 
// @desc Create a new book
// @route POST /api/v1/books/create-book
// @access Private (Admin)
const postBook = async (req, res) => {
  const newBook = new Book(req.body)
  await newBook.save()
  res.status(StatusCodes.CREATED).json(newBook)
}
 
// @desc Get all books with filtering, sorting, and pagination
// @route GET /api/v1/books
// @access Public
const getAllBooks = async (req, res) => {
  const { title, author, category, sort, numericFilters } = req.query
  const queryObject = {}
 
  Iif (author) {
    queryObject.author = author
  }
 
  Iif (category) {
    queryObject.categories = category
  }
 
  Iif (title) {
    queryObject.title = { $regex: title, $options: 'i' }
  }
 
  Iif (numericFilters) {
    const operatorMap = {
      '>': '$gt',
      '>=': '$gte',
      '=': '$eq',
      '<': '$lt',
      '<=': '$lte',
    }
    const regEx = /\b(<|>|>=|=|<|<=)\b/g
    let filters = numericFilters.replace(
      regEx,
      (match) => `-${operatorMap[match]}-`,
    )
    // Only allowing filtering on 'price' for now, as 'rating' is nested in reviews
    const options = ['price']
    filters = filters.split(',').forEach((item) => {
      const [field, operator, value] = item.split('-')
      if (options.includes(field)) {
        queryObject[field] = { [operator]: Number(value) }
      }
    })
  }
 
  let result = Book.find(queryObject)
 
  // Sort
  Iif (sort) {
    const sortList = sort.split(',').join(' ')
    result = result.sort(sortList)
  } else {
    result = result.sort('-createdAt')
  }
 
  // Pagination
  const page = Number(req.query.page) || 1
  const limit = Number(req.query.limit) || 10
  const skip = (page - 1) * limit
 
  // Get total count for the query (before pagination)
  const totalBooks = await Book.countDocuments(queryObject)
  const totalPages = Math.ceil(totalBooks / limit)
 
  result = result.skip(skip).limit(limit).populate('categories', 'name')
 
  const books = await result
  res
    .status(StatusCodes.OK)
    .json({ books, totalBooks, currentPage: page, totalPages })
}
 
// @desc Get a single book by ID
// @route GET /api/v1/books/:id
// @access Public
const getSingleBook = async (req, res) => {
  const book = await Book.findById(req.params.id).populate('categories', 'name')
  if (!book) {
    throw new NotFoundError(`Book with id ${req.params.id} not found`)
  }
  res.status(StatusCodes.OK).send(book)
}
 
// @desc Update a book by ID
// @route PUT /api/v1/books/edit/:id
// @access Private (Admin)
const updateBook = async (req, res) => {
  const updatedBook = await Book.findByIdAndUpdate(req.params.id, req.body, {
    new: true,
    runValidators: true, // Ensure validators run on update
  })
  if (!updatedBook) {
    throw new NotFoundError(
      `Book with id ${req.params.id} not found for update`,
    )
  }
  res.status(StatusCodes.OK).send(updatedBook)
}
 
// @desc Delete a book by ID
// @route DELETE /api/v1/books/:id
// @access Private (Admin)
const deleteBook = async (req, res) => {
  const { id } = req.params
  const deletedBook = await Book.findByIdAndDelete(id)
  if (!deletedBook) {
    throw new NotFoundError(`Book with id ${id} not found for deletion`)
  }
  res.status(StatusCodes.OK).send(deletedBook)
}
 
// @desc Add a review to a book
// @route POST /api/v1/books/:id/create-review
// @access Private (User)
const postReview = async (req, res) => {
  const { id: bookId } = req.params
  const userId = req.user?.userId
  const { description, rating } = req.body
 
  if (!userId) {
    throw new UnauthenticatedError(
      'Authentication is required to add a review.',
    )
  }
 
  if (rating === undefined) {
    throw new BadRequestError('Rating is required for a review.')
  }
 
  const book = await Book.findById(bookId)
 
  if (!book) {
    throw new NotFoundError(`Book with ID ${bookId} not found`)
  }
 
  const review = {
    user: userId,
    description,
    rating,
  }
 
  const existingReview = book.review.find(
    (r) => r.user.toString() === userId.toString(),
  )
  if (existingReview) {
    throw new BadRequestError('You have already reviewed this book.')
  }
 
  book.review.push(review)
  await book.save()
 
  res.status(StatusCodes.CREATED).json(book)
}
 
// @desc Delete a review from a book
// @route DELETE /api/v1/books/:id/reviews/:reviewId
// @access Private (Admin or User who owns the review)
const deleteReview = async (req, res) => {
  const { bookId, reviewId } = req.params
  const userId = req.user.userId
 
  if (!userId) {
    throw new UnauthenticatedError(
      'Authentication is required to delete a review.',
    )
  }
 
  const book = await Book.findById(bookId)
 
  if (!book) {
    throw new NotFoundError(`No book with id ${bookId}`)
  }
 
  const reviewIndex = book.review.findIndex(
    (r) => r._id.toString() === reviewId,
  )
 
  if (reviewIndex === -1) {
    throw new NotFoundError(
      `No review with id ${reviewId} found for this book.`,
    )
  }
 
  book.review.splice(reviewIndex, 1)
 
  await book.save()
 
  res.status(StatusCodes.OK).json({ msg: 'Success! Review removed from book.' })
}
 
module.exports = {
  postBook,
  getAllBooks,
  getSingleBook,
  updateBook,
  deleteBook,
  postReview,
  deleteReview,
}