Reputation: 1142
I have a HTTP-triggered function which returns an increment number every time the endpoint is called. The code looks like this:
export const reserve = functions.https.onRequest((req, resp) => {
cors(req, resp, async () => {
if (req.method.toLowerCase() !== 'post') {
resp.status(405);
resp.end();
} else {
const path = `counter`;
const ref = firebase.database().ref(path);
const oldCount = (await ref.once('value')).val();
await ref.set(oldCount + 1);
resp.status(200).send({
number: oldCount
});
resp.end();
}
});
});
The problem is, if 2 invocations are very close to each other, is there a chance that the function can return the same number? If so, is there a way to prevent this?
Upvotes: 3
Views: 401
Reputation: 6878
Yes, you are right, there can be an issue like this. I am not familiar with firebase but look for something that allows you to directly increment that number in firebase without having to fetch it first. This will be an atomic operation and ensure that you don't encounter the issue you described.
If this is not possible with firebase then you might have to setup a server in the middle that somehow keeps the record of the counter. Each time you want to increment/decrement the number, the request goes through your server which performs the operation on the cache first and then completes the request by calling the Firebase API.
Update: Here is how Firebase recommends this:
ref.transaction(function (current_value) {
return (current_value || 0) + 1;
});
Upvotes: 2