Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a variable from outside the function to a firebase event

Below is my code running on nodeJS server, I am trying to send an SMS message as soon as the 'child_added' event is triggered

// Twilio Credentials
var accountSid = '<AccountSid>';
var authToken = '<authToken>';


var twilio = require("twilio");
var client = new twilio.RestClient(accountSid, authToken);

// TWILIO Function
client.messages.create({
    to: "+12432056980", // This need to be obtained from firebase
    from: "+14352058756",
    body: "Hey There! Good luck on the bar exam!"
}, function(err, message) {
    console.log(message.sid);
});

Below is the event that is triggered as soon as a child is added to firebase database, I would like to call the TWILIO Function (shown above) as soon as as the below event is triggered and also pass it the mobile number variable from the below function.

ref.limitToFirst(1).on('child_added', function(snapshot) { // This function triggers the event when a new child is added
  var userDetails = snapshot.val();
  var mobileNumber = userDetails.mobileNumber;

  //*** I would like to call the TWILIO CODE  at this point and pass it the 'mobileNumber' parameter

});
like image 563
kurrodu Avatar asked Jul 29 '16 15:07

kurrodu


1 Answers

If the two operations are within the same file you can just wrap the Twilio call in a function and call it from within the Firebase operation like so...

function sendSMS(dest, msg) {
    client.messages.create({
        to: dest,
        from: "+14352058756",
        body: msg
    }, function(err, message) {
        console.log(message.sid);
    });
}

ref.limitToFirst(1).on('child_added', function(snapshot) {
  var userDetails = snapshot.val();
  var mobileNumber = userDetails.mobileNumber;

  sendSMS(mobileNumber, "Hey There! Good luck on the bar exam!");
});

If the Twilio operation is in a different file, you can export it and require where you use Firebase

//twiliofile.js
module.exports.sendSMS = function(dest, msg) {
    client.messages.create({
        to: dest,
        from: "+14352058756",
        body: msg
    }, function(err, message) {
        console.log(message.sid);
    });
}

-

//firebasefile.js
var sms = require('./twiliofile.js');

ref.limitToFirst(1).on('child_added', function(snapshot) {
  var userDetails = snapshot.val();
  var mobileNumber = userDetails.mobileNumber;

  sms.sendSMS(mobileNumber, "Hey There! Good luck on the bar exam!");
});
like image 128
m_callens Avatar answered Oct 15 '22 22:10

m_callens