Skip to content

Commit

Permalink
refactor: server side code refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
vit718 committed Jul 13, 2023
1 parent 20fc873 commit 9b89d05
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 21 deletions.
22 changes: 11 additions & 11 deletions server/controller/colorCtrl.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ const createColor = asyncHandler(async (req, res) => {
// Get title from request body
const { title } = req.body;
// Create a new color with the title
const brand = await Color.create({ title });
const color = await Color.create({ title });
// Return response with success message and created color
res.status(201).json({
success: true,
message: "Color created successfully",
brand,
color,
});
} catch (error) {
throw new Error(error);
Expand All @@ -29,14 +29,14 @@ const updateColor = asyncHandler(async (req, res) => {
// Validate the id
validateMongoDbId(id);
// Find and update the color with the given id
const brand = await Color.findByIdAndUpdate(id, req.body, {
const color = await Color.findByIdAndUpdate(id, req.body, {
new: true,
});
// Return response with success message and updated color
res.status(200).json({
success: true,
message: "Color updated successfully",
brand,
color,
});
} catch (error) {
throw new Error(error);
Expand All @@ -51,12 +51,12 @@ const deleteColor = asyncHandler(async (req, res) => {
// Validate the id
validateMongoDbId(id);
// Find and delete the color with the given id
const brand = await Color.findByIdAndDelete(id);
const color = await Color.findByIdAndDelete(id);
// Return response with success message and deleted color
res.status(200).json({
success: true,
message: "Color deleted successfully",
brand,
color,
});
} catch (error) {
throw new Error(error);
Expand All @@ -71,28 +71,28 @@ const getColor = asyncHandler(async (req, res) => {
// Validate the id
validateMongoDbId(id);
// Find the color with the given id
const brand = await Color.findById(id);
const color = await Color.findById(id);
// Return response with success message and fetched color
res.status(200).json({
success: true,
message: "Color fetched successfully",
brand,
color,
});
} catch (error) {
throw new Error(error);
}
});

// Get all brands
// Get all colors
const getAllColors = asyncHandler(async (req, res) => {
try {
// Find all colors
const brands = await Color.find({});
const colors = await Color.find({});
// Return response with success message and fetched colors
res.status(200).json({
success: true,
message: "Colors fetched successfully",
brands,
colors,
});
} catch (error) {
throw new Error(error);
Expand Down
32 changes: 23 additions & 9 deletions server/controller/userCtrl.js
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,7 @@ const resetPassword = asyncHandler(async (req, res) => {
// Get wishlist
const getWishlist = asyncHandler(async (req, res) => {
// Log the user from the request
console.log(req.user);
// console.log(req.user);
// Get the user id from the request user
const { _id } = req.user;
// Validate the MongoDB Id
Expand All @@ -460,10 +460,6 @@ const getWishlist = asyncHandler(async (req, res) => {

// ADD to User Cart
const userCart = asyncHandler(async (req, res) => {
// Log the request body
console.log(req.body);
// Log the user id from the request user
console.log(req.user._id);
// Get the cart from the request body
const { cart } = req.body;
// Get the user id from the request user
Expand Down Expand Up @@ -505,16 +501,12 @@ const userCart = asyncHandler(async (req, res) => {
for (let i = 0; i < products.length; i++) {
cartTotal = cartTotal + products[i].price * products[i].count;
}
// Log the cart total
console.log("cartTotal", cartTotal);
// Create a new cart with the products, total and user id
let newCart = await new Cart({
products,
cartTotal,
orderedBy: user._id,
}).save();
// Log the new cart
console.log("new cart ----> ", newCart);
// Return a success response
res.status(200).json({
status: "success",
Expand Down Expand Up @@ -714,6 +706,7 @@ const getOrders = asyncHandler(async (req, res) => {
// Find the orders associated with the user and populate the product details
const UserOrders = await Order.findOne({ orderedBy: _id })
.populate("products.product")
.populate("orderedBy")
.exec();

// Return the response with the orders details
Expand All @@ -727,6 +720,26 @@ const getOrders = asyncHandler(async (req, res) => {
}
});

// Get all orders
const getAllOrders = asyncHandler(async (req, res) => {
try {
// Find all the orders and populate the product details
const orders = await Order.find()
.populate("products.product")
.populate("orderedBy")
.exec();

// Return the response with the orders details
res.status(200).json({
status: "success",
message: "All orders fetched successfully",
orders,
});
} catch (error) {
throw new Error(error);
}
});

// update order status
const updateOrderStatus = asyncHandler(async (req, res) => {
// Get the status from the request body
Expand Down Expand Up @@ -781,4 +794,5 @@ module.exports = {
createOrder,
getOrders,
updateOrderStatus,
getAllOrders,
};
2 changes: 2 additions & 0 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const bodyParser = require("body-parser");
const { notFound, errorHandler } = require("./middlewares/errorHandler");
const cookieParser = require("cookie-parser");
const morgan = require("morgan");
const cors = require("cors");

// Initialize the Express app
const app = express();
Expand All @@ -25,6 +26,7 @@ dbConnect();

// Use middlewares
app.use(morgan("dev")); // Log every request to the console using the dev format for Morgan
app.use(cors()); // Allow cross origin resource sharing
app.use(bodyParser.json()); // Parse incoming JSON requests
app.use(bodyParser.urlencoded({ extended: false })); // Support parsing of x-www-form-urlencoded data
app.use(cookieParser()); // Parse cookies attached to incoming client requests
Expand Down
34 changes: 33 additions & 1 deletion server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
"body-parser": "^1.20.2",
"cloudinary": "^1.36.1",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"express-async-handler": "^1.2.0",
"jsonwebtoken": "^9.0.0",
"mongoose": "^7.0.3",
"morgan": "^1.10.0",
Expand Down
2 changes: 2 additions & 0 deletions server/routes/authRoute.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const {
createOrder,
getOrders,
updateOrderStatus,
getAllOrders,
} = require("../controller/userCtrl");

// Import the authMiddleware and isAdmin middleware functions
Expand Down Expand Up @@ -57,6 +58,7 @@ router.post("/cart/cash-order", authMiddleware, createOrder);
// Define routes for retrieving user data
router.get("/all-users", getallUsers);
router.get("/get-orders", authMiddleware, getOrders);
router.get("/get-all-orders", authMiddleware, isAdmin, getAllOrders);
router.get("/refresh", handleRefreshToken);
router.get("/logout", logout);
router.get("/wishlist", authMiddleware, getWishlist);
Expand Down

0 comments on commit 9b89d05

Please sign in to comment.