Reputation: 1179
I started using Firebase functions to collect data from external APIs because if I did them through the client itself, they were blocked by CORS. So I get the data from the firebase node server with the function.
I have tested and caching the function works fine. If I call the same function during that hour, the firebase function does not execute and returns the cached data.
The code looks like this:
exports.myFunction = functions.https.onRequest((req, res) => {
cors(req, res, () => {
axios
.get("EXTERNAL_API_URL")
.then(function (response) {
res.set("Cache-Control", "public, max-age=3600, s-maxage=3600");
res.send({ data: response.data });
})
.catch(function (error) {
res.end();
});
});
});
I wonder if this option is the right one or would it be better to create a scheduled function that every 1h save/edit the string data from external API in a Firestore document. So the users gets the data from Firestore.
What would be the most recommended? Considering that the data from the external APIs will be the same for all users, there are no frequent changes and it's not necessary to be authenticated or logged in to get that data.
Thanks in advance!
Upvotes: 1
Views: 266
Reputation: 1170
Given that your data doesn’t change frequently, I think that using caching is better. If you use a scheduled function to store data in Firestore, then you will have to use a query which in turn increases the cost, as the pricing is dependent on the number of queries performed.
You can also use below two methods to avoid returning stale data to your users:
Upvotes: 2