SimonartM
SimonartM

Reputation: 688

Wait for firebase cloud trigger function to end before launching http request

Question

I have a frontend user-registration page. Once the user clicks on 'Register', a user document gets created in my firestore database. I made a 'onCreate' trigger function which listens to new user-documents getting created. This trigger function creates and updates other documents in my database (it adds extra information and creates some documents based on the user-document that just got created).

Once the user clicks on Register in my frontend, they are redirected to a new page. On initState that new page, it makes a http (cloud function) request which needs this newly created info made by my trigger function to correctly make his response. The thing is, this HTTP-request gets launched before my trigger function ends, this causes the HTTP function to error, because it cannot yet find the information needed, because the trigger function hasn't ended and hasn't fully updated the database yet.

Does anyone know how to resolve this problem? The first thing I did, which was just a very ugly and quick workaround, was to have a delay in my frontend of a few seconds, right after the onclick 'register', so that it would delay it's redirecting to the new page, and therefore delay the http-request. But this was just a temporary solution. I would like to have a real solution now. Is there a way to tell the http-request to not run while this specific trigger-function is running? Or if not possible, is there another way to architecture my functions or my frontend to prevent this? I've thought about it, and tried to research someone with the same problem, but I can't find any questions regarding this. (This scares me a little, 'cause that makes me feel like I'm missing something basic).

If you could help, thanks in advance.

Upvotes: 2

Views: 908

Answers (1)

Kolban
Kolban

Reputation: 15246

What I am hearing here is that you have a classic race condition. I am understanding that your user click "Register" and that causes a new document to be added to the database. There is then a trigger on that insertion which updates other documents/fields. It is here that you have introduced parallelism and hence the race.

Your design needs to change such that there is a "signal" sent back from GCP when the updates that were performed asynchronously have completed. Since the browser doesn't receive unsolicited signals, you will have to design a solution where your browser calls back to GCP such that the call doesn't return until the asynchronous changes have been completed. One way might be to NOT have an onCreate trigger but instead have the browser explicitly call a Cloud Function to perform the updates after the initial insertion (or even a Cloud Function that performs the insertion itself). The Cloud Function should not return until the data is consistent and ready to be read back by the browser.

Upvotes: 4

Related Questions