How to ensure that functions are performed?

I have an HTTP-triggered function that returns the 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 the two calls are very close to each other, is there a chance the function could return the same number? If so, is there a way to prevent this?

+3


source to share


1 answer


Yes, you are right, there may be such a problem. I'm not familiar with firebase, but look for something that allows you to directly increment that number in firebase without picking it up first. It will be an atomic operation and make sure you don't run into the problem you described.

If this is not possible in firebase, you might have to set up a server in the middle that keeps the counter record somehow. Every time you want to increment / decrement the number, the request goes through your server, which first performs an operation in the cache and then completes the request by calling the Firebase API.



Update: This is how Firebase recommends it :

ref.transaction(function (current_value) {
  return (current_value || 0) + 1;
});

      

+2


source







All Articles