Firebase Cloud Function being called twice

Asked

Viewed 31 times

0

I have the following function:

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');

exports.myFunction = functions.database.ref('/my_node/{myId}/status').onCreate(event => {
  const data = event.data.val();
  if (data == 'STATE01') {
    return event.data.ref.set('STATE02');
  }
});

I’m using onCreate, then the function should be called only once and not twice. Because this is happening?

View the logs:

9:29:27.975 pm myFunction Function Execution Took 33 ms, finished with status: 'ok'

9:29:27.943 PM myFunction Function Execution Started

9:29:27.875 pm myFunction Function Execution Took 1059 ms, finished with status: 'ok'

9:29:26.818 pm myFunction Function Execution Started

1 answer

0

That’s because you’re making one more set() in their role. And onCreate is executed whenever a set. To avoid the second execution, you can replace the set for update:

exports.myFunction = functions.database.ref('/my_node/{myId}/status').onCreate(event => {
  const data = event.data.val();
  if (data == 'STATE01') {
    return event.data.ref.parent.update({status:'STATE02'});
  }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.