All files / bc-mongodb-implementation-demo/src/features/categories category.controller.js

19.14% Statements 9/47
0% Branches 0/19
0% Functions 0/5
19.14% Lines 9/47

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 1052x 2x 2x         2x                       2x                                                           2x                       2x                             2x                                         2x              
const Category = require('./category.model')
const { StatusCodes } = require('http-status-codes')
const { NotFoundError, BadRequestError } = require('../../errors')
 
// @desc Create a new category
// @route POST /api/v1/categories
// @access Private (Admin)
const createCategory = async (req, res) => {
  const { name, description } = req.body
  if (!name) {
    throw new BadRequestError('Category name is required')
  }
  const category = await Category.create({ name, description })
  res.status(StatusCodes.CREATED).json({ category })
}
 
// @desc Get all categories with pagination
// @route GET /api/v1/categories
// @access Public
const getAllCategories = async (req, res) => {
  const { page = 1, limit = 10, sort = 'name' } = req.query
 
  const pageNumber = parseInt(page, 10)
  const limitNumber = parseInt(limit, 10)
  const skip = (pageNumber - 1) * limitNumber
 
  let sortOption = {}
  if (sort) {
    const sortDirection = sort.startsWith('-') ? -1 : 1
    const sortField = sort.startsWith('-') ? sort.substring(1) : sort
    sortOption[sortField] = sortDirection
  } else {
    sortOption.name = 1 // Default sort by name ascending
  }
 
  const categories = await Category.find({})
    .sort(sortOption)
    .skip(skip)
    .limit(limitNumber)
 
  const totalCategories = await Category.countDocuments({})
  const totalPages = Math.ceil(totalCategories / limitNumber)
 
  res.status(StatusCodes.OK).json(categories)
}
 
// @desc Get a single category by ID
// @route GET /api/v1/categories/:id
// @access Public
const getCategoryById = async (req, res) => {
  const { id: categoryId } = req.params
  const category = await Category.findById(categoryId)
  if (!category) {
    throw new NotFoundError(`Kategorie s ID ${categoryId} nebyla nalezena.`)
  }
  res.status(StatusCodes.OK).json({ category })
}
 
// @desc Update a category by ID
// @route PUT /api/v1/categories/:id
// @access Private (Admin)
const updateCategory = async (req, res) => {
  const { id } = req.params
  const category = await Category.findByIdAndUpdate(id, req.body, {
    new: true,
    runValidators: true,
  })
  if (!category) {
    throw new NotFoundError(`No category with id ${id}`)
  }
  res.status(StatusCodes.OK).json(category)
}
 
// @desc Delete a category by ID
// @route DELETE /api/v1/categories/:id
// @access Private (Admin)
const deleteCategory = async (req, res) => {
  const { id } = req.params
 
  // First check if any books are using this category
  const Book = require('../books/book.model')
  const booksUsingCategory = await Book.countDocuments({ categories: id })
 
  if (booksUsingCategory > 0) {
    return res.status(StatusCodes.BAD_REQUEST).json({
      message: `Cannot delete this category because it is used by ${booksUsingCategory} books. Please remove the category from all books first.`,
    })
  }
 
  const category = await Category.findByIdAndDelete(id)
  if (!category) {
    throw new NotFoundError(`No category with id ${id}`)
  }
 
  res.status(StatusCodes.OK).json(category)
}
 
module.exports = {
  createCategory,
  getAllCategories,
  getCategoryById,
  updateCategory,
  deleteCategory,
}