I have this situation, where in I don’t have the required API for the front end I am trying to implement. So I’m trying to solve this by having an intermediary cloud function that fetches all data from the original backend server and then does a simple filter to generate the data i need in my front end. The only issue with this approach is this, since I am fetching all data from the backend on every call, this becomes heavy on the original backend server in terms of database reads. Also I’m having to wait for the call to finish from the front end.
How can i Memoize my Netlify AWS Lambda Function, such that it periodically fetches data from the original server, say once every 2 hours and then caches it, so when i call from my front end the cloud function doesn’t have to talk to the original backend server and can just send me the cached data.
I understand that doing this will result in getting data that is old, ie, products that could be sold out. To mitigate this to some extend, I’m thinking I will call the original server to check the stock availability of the products returned by the Netlify AWS Lambda server. The only issue remaining is that when new Products are added they will have a delay period equaling the cache expiry time. I’m okay with that trade off, do let me know if there’s a better approach that can deal with that too, Thank You.
CODE
import fetch from 'node-fetch';
const {API_TOKEN} = process.env;
exports.handler = async (event,context,callback) => {
const activeCategoriesRes = await fetch('https://api.example.com/category/GetActiveCategories',{
method: 'GET',
headers: {'APIToken': API_TOKEN}
});
const activeCategoriesData = await activeCategoriesRes.json();
const categories = activeCategoriesData.result;
const categoriesIdArray = categories.map(category => category.CategoryId);
const productsNested = await Promise.all(categoriesIdArray.map(categoryID => {
const categoryProductsRes = await fetch(`http://api.example.com/Product/GetProductSearchByCategory`,{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'APIToken': API_TOKEN
},
body: JSON.stringify({
"CategoryID": CategoryID,
"Search": " ",
"lstBrand": [],
"lstColor": [],
"lstSize": [],
"PriceFrom": 0,
"PriceTo": 0,
"MaxPrice": 0,
"Page": 1,
"Show": 9999,
"UserID": ""
})
})
const categoryProductsData = await categoryProductsRes.json();
return categoryProductsData.result;
}));
const productsList = productsNested.flat();
const hotDeals = productsList.filter(product => product.DiscountPercentage > 15 && product.SellingPrice > 50);
callback(null,{
statusCode: 200,
body: JSON.stringify(hotDeals)
})
}