1

I have a problem with Cloud Functions.

I am making a reservation system. When an admin accepts a reservation, I make this call on the client:

reservationRef.update({
  handled: true,
  lastHandledBy: AUTH.currentUser.uid,
  timestamp: TIMESTAMP
})

Here is how the whole reservation looks like:

roomId: number
address: string
name: string
tel: string
message: string
email: string
from: number
to: number
timestamp: date
lastHandledBy: string
handled: boolean
adults: number
children: number

In Cloud Functions, I have a function that triggers when the reservation is updated, so I can send a confirmation e-mail to the user. It looks like this:

exports.reservationChanged = reservationRef
       .onUpdate(({before, after}, {params: {reservationId}}) => {
         before = before.data()
         after = after.data()
         // Reservation accepted
         if (!before.handled && after.handled) {
           return email.reservationAccepted(reservationId, after)
         }
       }

For some reason though, it is triggered twice and sends two e-mails, and I don't know why. I update the reservation with a simple .update()

What did I do wrong?

Thanks

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Balázs Orbán
  • 559
  • 1
  • 4
  • 26
  • What exactly is `reservation` in the first bit of code? What exactly is `reservationRef` in the second bit? – Doug Stevenson Apr 22 '18 at 20:41
  • Sorry, both should be `reservationRef`, and it is the same as for example `firebase.database().ref("reservations/"+reservationId)` So the reference point in the database, where the update/change is happening – Balázs Orbán Apr 22 '18 at 20:50
  • Are you sure you're only calling `.update()` once? – Colin Ricardo Apr 22 '18 at 20:55
  • Could you please edit your question to update your code to be more specific about the values whose definitions are not shown? – Doug Stevenson Apr 22 '18 at 20:58
  • @Colin yes, I am sure. and Doug Stevenson, I updated the question now. – Balázs Orbán Apr 22 '18 at 21:09
  • 1
    Is it possible that `before = before.data() after = after.data()` is triggering a change and causing it to fire twice? Try using a different variable name there. – Colin Ricardo Apr 22 '18 at 21:11
  • What is the minimal code in `reservationAccepted` with which you can reproduce the problem? I.e. comment out everything that can't be related, if you can then still reproduce it, show us that minimal code. – Frank van Puffelen Apr 22 '18 at 22:08

1 Answers1

1

The problem was solved. I forgot to deploy my new code. In the old one, I used 2 .set() methods instead of one .update() on the client to update the reservation, which caused separate .onUpdate triggerings in Cloud Functions.

Balázs Orbán
  • 559
  • 1
  • 4
  • 26