diff --git a/controllers/userOrderControl.js b/controllers/userOrderControl.js index 71b457e..0042257 100644 --- a/controllers/userOrderControl.js +++ b/controllers/userOrderControl.js @@ -99,12 +99,12 @@ exports.getRecommendation = async (req, res, next) => { const userID = req.params.user_id; let orders = await Order.find({ user_id: userID }) .sort({ createdAt: -1 }) - .limit(2); // Get the last 5 orders + .limit(5); // Get the last 5 orders let recommendedItemsSet = new Set(); - // Fetch recommendations for default items + // Fetch recommendations for default items in parallel const defaultItems = ["Samosa", "Pav Bhaji"]; - for (let itemName of defaultItems) { + const defaultRecommendationsPromises = defaultItems.map(async (itemName) => { let foodItemTitleCase = toTitleCase(itemName); try { const response = await axios.get( @@ -123,10 +123,10 @@ exports.getRecommendation = async (req, res, next) => { } catch (e) { console.log(e); } - } + }); - // Process orders for additional recommendations - for (let order of orders) { + // Process orders for additional recommendations in parallel + const ordersRecommendationsPromises = orders.map(async (order) => { const item = order.items[0]; // Assuming you want the first item of each order const itemName = item.name; let foodItemTitleCase = toTitleCase(itemName); // Convert the food item name to Title Case @@ -148,7 +148,14 @@ exports.getRecommendation = async (req, res, next) => { } catch (e) { console.log(e); } - } + }); + + // Execute default recommendations and orders recommendations in parallel, but don't wait for default recommendations to complete + await Promise.all(ordersRecommendationsPromises); + + // After orders recommendations are complete, wait for default recommendations to finish + await Promise.all(defaultRecommendationsPromises); + const recommendedItems = Array.from(recommendedItemsSet).map((item) => JSON.parse(item) ); @@ -159,6 +166,8 @@ exports.getRecommendation = async (req, res, next) => { } }; + + function toTitleCase(str) { return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();