I came up with this solution, I don’t if it’s a proper implementation, please let me know if there is a better implementation.
import fetch from 'node-fetch';
const {API_TOKEN,USER_ID} = process.env;
let data = [];
let lastUpdate = 0;
exports.handler = async (event,context,callback) => {
const fetchHotDeals = async () => {
try{
const activeCategoriesRes = await fetch('http://api.example.com/category/GetActiveCategories',{
method: 'GET',
headers: {'APIToken': API_TOKEN}
});
const activeCategoriesData = await activeCategoriesRes.json();
const allCategories = activeCategoriesData.result;
const subCategories = allCategories.filter(category => category.ParentCategoryId !== 0);
const categoriesIdArray = subCategories.map(category => category.CategoryId);
const productsNested = await Promise.all(categoriesIdArray.map( async categoryID => {
const categoryProductsRes = await fetch(`http://api.example.com/Product/GetProductByCategory?CategoryID=${categoryID}&UserID=${USER_ID}`,{
method: 'GET',
headers: {'APIToken': API_TOKEN }
});
const categoryProductsData = await categoryProductsRes.json();
return categoryProductsData.result;
}))
const productsList = productsNested.flat();
const hotDeals = productsList.filter(product => product.DiscountPercentage > 15 && product.SellingPrice > 50);
return hotDeals;
} catch (error) {
callback(new Error("unable to generate hot deals"))
}
}
const currentTime = new Date().getTime();
if(data.length === 0 || (currentTime-lastUpdate > 3600000)){ /* 3600000 = 1hour */
const hotDeals = await fetchHotDeals();
data = [...hotDeals];
lastUpdate = new Date().getTime();
callback(null,{
statusCode: 200,
body: JSON.stringify(data)
});
} else {
callback(null,{
statusCode: 200,
body: JSON.stringify(data)
});
}
}