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

Below my code works on a nodeJS server, I try to send an SMS as soon as the 'child_added' event 'child_added'

 // 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 an event that is fired as soon as a child is added to the firebase database , I would like to call the TWILIO function (shown above) as soon as the next event is fired, and also pass the mobile number variable from the function below.

 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 }); 
+6
source share
1 answer

If two operations are inside the same file, you can simply wrap the Twilio call in a function and call it from Firebase , for example, like this ...

 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 another file, you can export it and require that 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!"); }); 
+5
source

All Articles