Skip to content

Commit

Permalink
chore: parallelize
Browse files Browse the repository at this point in the history
  • Loading branch information
tusharbansal22 committed Apr 10, 2024
1 parent 8431d21 commit 554728e
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions controllers/userOrderControl.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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
Expand All @@ -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)
);
Expand All @@ -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();
Expand Down

0 comments on commit 554728e

Please sign in to comment.