【问题标题】:How to pass a variable from outside the function to a firebase event如何将函数外部的变量传递给firebase事件
【发布时间】:2016-07-29 15:07:40
【问题描述】:

下面是我在 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

});

【问题讨论】:

  • 您能否详细说明您究竟需要做什么,我不知道 twilio 是如何工作的,或者您所说的 firebase 是什么意思。传递值就像使用参数一样简单,我没有看到问题?
  • 事件处理程序位于何处?与上面的 twilio 需要相同的文件吗?
  • @Dellirium 我已经简化了我的问题,Firebase 是来自 Google 的实时数据库,Twilio 为开发人员提供使用他们的 API 发送 SMS 的功能。
  • @10100111001 是的,事件处理程序与 twilio require 位于同一文件中。
  • @kurrodu 调用 twilio 函数时是否收到错误消息?您遇到的具体问题是什么?

标签: javascript node.js firebase firebase-realtime-database twilio


【解决方案1】:

如果这两个操作在同一个文件中,您只需将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!");
});

【讨论】:

  • 嘿 m_callens,感谢您在 Twilio 标记社区中的帮助。我可以给你寄件衬衫来表示感谢吗?发送电子邮件至 mspeir@twilio.com 了解详情。
猜你喜欢
  • 1970-01-01
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
  • 2021-07-11
  • 2010-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多