api/resources/Brands/BrandsController.js
2025-02-06 09:42:09 +05:30

335 lines
8.7 KiB
JavaScript

import mongoose from "mongoose";
import { BrandModel } from "./BrandsModel.js";
import cloudinary from "../../Utils/cloudinary.js";
// Get all Brands
export const getBrands = async (req, res) => {
try {
// const PAGE_SIZE = parseInt(req.query.show) || 10;
// const page = parseInt(req.query.page) || 1;
// const skip = (page - 1) * PAGE_SIZE;
let filter = {};
// Search by brandName if provided
if (req.query.brandName) {
filter.brandName = {
$regex: new RegExp(req.query.brandName, "i"), // Case-insensitive search
};
}
// Get total number of brands matching the filter
const total = await BrandModel.countDocuments(filter);
// Fetch brands with pagination and filtering
const brands = await BrandModel.find(filter)
// .limit(PAGE_SIZE)
// .skip(skip)
.sort({ createdAt: -1 })
.exec();
// Return the paginated and filtered brands list
res.status(200).json({
success: true,
total_data: total,
// total_pages: Math.ceil(total / PAGE_SIZE),
// current_page: page,
brands,
});
} catch (error) {
// Handle server error
res.status(500).json({
success: false,
message: error.message || "Something went wrong",
});
}
};
// Add new Brand
// export const addBrand = async (req, res) => {
// const { brandName } = req.body;
// if (!req?.user) {
// return res.status(400).json({ message: "Please login!" });
// }
// try {
// if (!mongoose.Types.ObjectId.isValid(req.user._id)) {
// return res.status(400).json({ message: "Please login again." });
// }
// if (!brandName) {
// return res.status(400).json({ message: "Please provide a brand name" });
// }
// const brand = await BrandModel.create({
// brandName,
// addedBy: req.user._id,
// });
// return res.status(201).json({ success: true, brand, message: "Brand added successfully" });
// } catch (error) {
// res.status(500).json({
// success: false,
// message: error.message || "Something went wrong",
// });
// }
// };
// // Update Brand
// export const updateBrand = async (req, res) => {
// const { _id } = req.params;
// const { brandName } = req.body;
// if (!req?.user) {
// return res.status(400).json({ message: "Please login!" });
// }
// if (!mongoose.Types.ObjectId.isValid(_id)) {
// return res.status(404).json({ message: "Invalid brand ID" });
// }
// try {
// const updatedBrand = await BrandModel.findByIdAndUpdate(
// _id,
// { brandName },
// { new: true, runValidators: true }
// );
// if (!updatedBrand) {
// return res.status(404).json({ message: "Brand not found" });
// }
// res.status(200).json({ success: true, updatedBrand, message: "Brand updated successfully" });
// } catch (error) {
// res.status(500).json({
// success: false,
// message: error.message || "Something went wrong",
// });
// }
// };
// // Delete Brand
// export const deleteBrand = async (req, res) => {
// const { _id } = req.params;
// if (!req?.user) {
// return res.status(400).json({ message: "Please login!" });
// }
// if (!mongoose.Types.ObjectId.isValid(_id)) {
// return res.status(404).json({ message: "Invalid brand ID" });
// }
// try {
// const deletedBrand = await BrandModel.findByIdAndDelete(_id);
// if (!deletedBrand) {
// return res.status(404).json({ message: "Brand not found" });
// }
// res.status(200).json({ success: true, deletedBrand, message: "Brand deleted successfully" });
// } catch (error) {
// res.status(500).json({
// success: false,
// message: error.message || "Something went wrong",
// });
// }
// };
export const addBrand = async (req, res) => {
const { brandName } = req.body;
const file = req.files?.image; // Assuming image is sent as a file
if (!req?.user) {
return res.status(400).json({ message: "Please login!" });
}
try {
if (!mongoose.Types.ObjectId.isValid(req.user._id)) {
return res.status(400).json({ message: "Please login again." });
}
if (!brandName) {
return res.status(400).json({ message: "Please provide a brand name" });
}
let image = {};
if (file) {
try {
const result = await cloudinary.v2.uploader.upload(file.tempFilePath, {
folder: "chemiNova/brand",
});
image = {
public_id: result.public_id,
url: result.secure_url,
};
} catch (uploadError) {
console.error("Error uploading image:", uploadError);
return res.status(500).json({
message: "Failed to upload image",
error: uploadError.message,
});
}
}
const brand = await BrandModel.create({
brandName,
image: image ? [image] : [],
addedBy: req.user._id,
});
return res
.status(201)
.json({ success: true, brand, message: "Brand added successfully" });
} catch (error) {
res.status(500).json({
success: false,
message: error.message || "Something went wrong",
});
}
};
export const updateBrand = async (req, res) => {
const { _id } = req.params;
const { brandName } = req.body;
const file = req.files?.image;
if (!req?.user) {
return res.status(400).json({ message: "Please login!" });
}
if (!mongoose.Types.ObjectId.isValid(_id)) {
return res.status(404).json({ message: "Invalid brand ID" });
}
try {
const brand = await BrandModel.findById(_id);
if (!brand) {
return res.status(404).json({ message: "Brand not found" });
}
let image = brand.image;
if (file) {
if (image.length > 0) {
await cloudinary.v2.uploader.destroy(image[0].public_id);
}
const result = await cloudinary.v2.uploader.upload(file.tempFilePath, {
folder: "chemiNova/brand",
});
image = [{ public_id: result.public_id, url: result.secure_url }];
}
const updatedBrand = await BrandModel.findByIdAndUpdate(
_id,
{ brandName, image },
{ new: true, runValidators: true }
);
res
.status(200)
.json({
success: true,
updatedBrand,
message: "Brand updated successfully",
});
} catch (error) {
res
.status(500)
.json({
success: false,
message: error.message || "Something went wrong",
});
}
};
export const deleteBrand = async (req, res) => {
const { _id } = req.params;
if (!req?.user) {
return res.status(400).json({ message: "Please login!" });
}
if (!mongoose.Types.ObjectId.isValid(_id)) {
return res.status(404).json({ message: "Invalid brand ID" });
}
try {
const brand = await BrandModel.findById(_id);
if (!brand) {
return res.status(404).json({ message: "Brand not found" });
}
if (brand.image.length > 0) {
await cloudinary.v2.uploader.destroy(brand.image[0].public_id);
}
await BrandModel.findByIdAndDelete(_id);
res
.status(200)
.json({ success: true, message: "Brand deleted successfully" });
} catch (error) {
res
.status(500)
.json({
success: false,
message: error.message || "Something went wrong",
});
}
};
export const deleteImageFromCloudinary = async (req, res) => {
const { public_id } = req.params;
// Ensure public_id is not empty
if (!public_id) {
return res.status(400).json({
success: false,
msg: "Public ID is required!",
});
}
const decodedPublicId = decodeURIComponent(public_id);
try {
// Step 1: Delete image from Cloudinary
const response = await cloudinary.v2.uploader.destroy(decodedPublicId);
if (response.result === "ok") {
// Step 2: Find the brand containing the image and update the database
const brand = await BrandModel.findOne({
"image.public_id": decodedPublicId,
});
if (!brand) {
return res.status(404).json({
success: false,
msg: "Brand not found with the given image!",
});
}
// Remove the image from the brand's image array
brand.image = brand.image.filter(
(img) => img.public_id !== decodedPublicId
);
// Step 3: Save the updated brand document
await brand.save();
return res.status(200).json({
success: true,
msg: "Image Deleted Successfully and removed from database!",
});
} else {
return res.status(400).json({
success: false,
msg: "Image deletion failed in Cloudinary!",
});
}
} catch (error) {
console.error("Error deleting image:", error); // Log error for debugging
return res.status(500).json({
success: false,
msg: error.message || "Something went wrong!",
});
}
};