Angie E
Angie E

Reputation: 81

Unable to query firebase in google cloud function

I have a firebase cloud function I can't get to run in the google cloud environment. I have the function running fine in every environment, including the local emulator, except for the actual cloud. It reaches the line where I make a query to the database for a user record (line 9 below). It will hang there for a while and then time out. Any ideas on why this might be happening? The event input is fine and has the correct user id.

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

admin.initializeApp(functions.config().firebase);
admin.database.enableLogging(true);

exports.createContract = functions.database.ref('/messages/{messageId}').onCreate(event => {
  let data = event.data.val();
  admin.database().ref(`/users/${data.user.id}`).once('value').then(user => {
    if (user.val() === null) {
      return reject(`User ${data.user.id} does not exist`);
    } else {
      data.userData.push(user.val());
    }
  }).catch((error) => {
      console.log(error);
  });
  // do other stuff here
});

The debug logs from the admin database connection look fine as well (prints this as soon as it reaches the problematic code, then continues to hang until it times out):

p:0: Browser went online.
p:0: Listen called for /users/-idabc123 default  
p:0: Making a connection attempt  
p:0: Auth token refreshed  
getToken() completed. Creating connection.  
c:0:0: Connection created  
c:0:0:0 Websocket connecting to wss://xxxxxx.firebaseio.com/.ws?v=5  
c:0:0:0 Websocket connected.  
c:0:0: Realtime connection established.  
p:0: connection ready  
p:0: reportStats {"c":{"sdk.node.4-8-2":1}}  
p:0: {"r":1,"a":"s","b":{"c":{"sdk.node.4-8-2":1}}}  
p:0: {"r":2,"a":"gauth","b":{"cred":"xxxxxxxxx"}}  
p:0: Listen on /users/-idabc123 for default  
p:0: {"r":3,"a":"q","b":{"p":"/users/-idabc123","h":""}}  
p:0: from server: {"r":1,"b":{"s":"ok","d":""}}  
c:0:0: Primary connection is healthy.  

Upvotes: 1

Views: 279

Answers (1)

Luke Stanyer
Luke Stanyer

Reputation: 1484

You need to return a promise to the Google Cloud function to let it know the async work you requested in .push has done or that you rejected a promise. Google Cloud is waiting for a promise and timing out.

exports.createContract = functions.database.ref('/messages/{messageId}').onCreate(event => {
  let data = event.data.val();
  // ADD RETURN BELOW
  return admin.database().ref(`/users/${data.user.id}`).once('value').then(user => { 
    if (user.val() === null) {
      //ADD 'PROMISE.'
      return Promise.reject(`User ${data.user.id} does not exist`)
    } else {
      return data.userData.push(user.val()); // AND ADD RETURN HERE
    }
  }).catch((error) => {
      console.log(error);
  });
  // do other stuff here
});

Upvotes: 1

Related Questions