Cache — A Cost-Effective Way to Consider When You Implement APIs!

Photo by Tobias Fischer on Unsplash
const collection = client.db("database").collection("collection");
const result = await collection.findOne({ id: ID });
if (result) {
// console.log("Cache found, return from cache, no needs for API");
return res.json(result);
} else {
// console.log("Cache not found, we are making the API call");
const result = await axios(config).then(function (response) {
return response.data.result;
}).catch(function (error) {
console.log(error);
});
if (result) {
// console.log("Creating new cache");
collection.insertOne({
result: result ? result : {},
});
// console.log("return the result from API");
res.json({
result: result ? result : {},
});
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Hanwen Zhang

Hanwen Zhang

21 Followers

Full-Stack Software Engineer at a Healthcare Tech Company | Document My Coding Journey | Improve My Knowledge | Share Coding Concepts in a Simple Way