Skip to content

Commit

Permalink
made relatedProducts service
Browse files Browse the repository at this point in the history
  • Loading branch information
Atallah0 committed Nov 4, 2023
1 parent 41c0134 commit b644557
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 11 deletions.
6 changes: 3 additions & 3 deletions controllers/orderController.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// imports
const { Cart, Order, OrderItem, Discount, Tax } = require('../models');
const { Cart, Order, OrderItem, /*Discount,*/ Tax } = require('../models');
const { asyncWrapper } = require('../middleware');
const { createCustomError } = require('../utils/errors/custom-error');
const {
Expand Down Expand Up @@ -72,8 +72,8 @@ const createOrder = asyncWrapper(async (req, res, next) => {

// Call the function to update product stock in the cart
await updateProductStockInCart(cartId);
const tax = await Tax.findByPk(taxId);
const tax = await Tax.findByPk(taxId);

// updating the total price of order based on the taxes and delivery fees
const totalPrice = Number(cart.totalPrice) + Number(tax.taxRate) + deliveryFee;
// creating the order
Expand Down
6 changes: 4 additions & 2 deletions controllers/productController.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,13 +174,16 @@ const getProduct = asyncWrapper(async (req, res, next) => {
where: { productId: id },
});

// Fetch related products
const relatedProducts = await ProductService.fetchRelatedProductsByProduct(id);
// Send a response with product and associated ratingReviews
return res.status(200).json({
success: true,
message: 'Product and RatingReviews fetched successfully',
data: {
product: product,
ratingReviews,
relatedProducts
},
});
} else {
Expand Down Expand Up @@ -406,8 +409,7 @@ const searchProducts = asyncWrapper(async (req, res, next) => {

// Log the products matching the keyword, category, or brand, and send a response
console.log(
`Products matching ${{ ...req.query }} have been called, products length= ${
products.length
`Products matching ${{ ...req.query }} have been called, products length= ${products.length
}`
);
res.status(200).json({
Expand Down
55 changes: 49 additions & 6 deletions services/productServices.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const { Product, Category, Brand } = require('../models');
const { development } = require('../config/config');
const { Op } = require('sequelize');
const sequelize = require('../utils/dataBaseConnection');


/**
* Retrieve a product's rating summary, including the total rating and rating count.
Expand All @@ -13,11 +15,11 @@ const getProductRatingSummary = async (product) => {

const rating = reviews
? (reviews
.map((review) => review.rating)
.reduce((acc, current) => acc + current, 0) /
reviews.length /
5) *
5
.map((review) => review.rating)
.reduce((acc, current) => acc + current, 0) /
reviews.length /
5) *
5
: 0;
const totalRating = Math.round(rating * 10) / 10;
const ratingCount = reviews ? reviews.length : 0;
Expand Down Expand Up @@ -122,7 +124,13 @@ const fetchProducts = async (options, page, itemsPerPage) => {
* @returns {Promise<object>} A structured response object containing product details and rating summary.
*/
const fetchProductById = async (id, options) => {
const product = await Product.findByPk(id, options);
const product = await Product.findByPk(id, {
...options,
include: [
{ model: Category, attributes: ['name'] },
{ model: Brand, attributes: ['name'] },
],
});

return await generateProductResponse(product);
};
Expand All @@ -140,9 +148,44 @@ const fetchHandPickedProducts = async (options) => {
return handPickedProducts;
};


/**
* Fetch related products by the category of a given product.
*
* @param {number} productId - The ID of the product to fetch related products for.
* @returns {Promise<object>} An object containing related products.
*/
const fetchRelatedProductsByProduct = async (productId, limit = 3) => {
const product = await Product.findByPk(productId);

if (!product) {
// Handle the case where the product is not found
throw new Error(`No product with id: ${productId} is found`);
}

const category = await Category.findByPk(product.categoryId);

if (!category) {
// Handle the case where the category is not found
throw new Error(`No category with id: ${product.categoryId} is found`);
}

const relatedProducts = await Product.findAll({
where: {
id: { [Op.not]: productId },
categoryId: category.id
},
order: sequelize.literal('RAND()'), // Order randomly
limit
});

return relatedProducts;
};

module.exports = {
fetchProducts,
fetchProductsWithCount,
fetchProductById,
fetchHandPickedProducts,
fetchRelatedProductsByProduct
};

0 comments on commit b644557

Please sign in to comment.