以下是我在nodeJS服务器上运行的代码,我在'child_added'
事件被触发后尝试send an SMS message
// 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);
});
以下是一旦将子项添加到firebase database时触发的事件,我想在触发下面的事件时立即调用TWILIO函数(如上所示)并将其传递给来自以下功能的手机号码变量。
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
});
答案 0 :(得分:5)
如果这两个操作在同一个文件中,您只需将Twilio
调用包装在一个函数中,然后在Firebase
操作中调用它,就像这样......
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!");
});
如果Twilio
操作位于其他文件中,您可以将其导出并要求您使用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!");
});