Firebase Cloud功能可在用户登录触发器上发送HTTP请求



对不起,但是我已经观看了詹妮弗人的所有七个视频,阅读文档并通过教程进行了工作,但我仍然看不到如何编写我的功能。我正在尝试编写一个获得IBM Watson语音到文本令牌的函数,该功能是通过此卷曲脚本获得的:

curl -X GET --user username:password --output token
"https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api"

即,将HTTP获取请求发送到URL,提供我的用户名和密码,然后将输出写入文件/javascript/services/token

这是我对功能的猜测。身份验证触发器包装nodejs http获取请求,而nodejs文件保存 fs.writefile

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.getWatsonToken = functions.auth.user().onCreate(event => { // authentication trigger
  var https = require('https');  // Nodejs http.request
  var options = {
    host: 'stream.watsonplatform.net',
    path: '/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api',
    username: groucho,
    password: swordfish
  };
  callback = function(response) {
    response.on('end', function () {
      console.log(response);
      fs.writeFile("/javascript/services/token", response);
    });
  }
  http.request(options, callback).end();
});

此功能有效:

// Node modules
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const request = require('request'); // node module to send HTTP requests
const fs = require('fs');
admin.initializeApp(functions.config().firebase);
exports.getWatsonToken = functions.database.ref('userLoginEvent').onUpdate(event => { // authentication trigger when user logs in
  var username = 'groucho',
      password = 'swordfish',
      url = 'https://' + username + ':' + password + '@stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api';
  request({url: url}, function (error, response, body) {
    var tokenService = "app.value('watsonToken','" + body + "');";
    fs.writeFile('../public/javascript/services/watsonTokenValue.js', tokenService, (err) => {
      if (err) throw err;
        console.log('The file has been saved!');
    }); // close fs.writeFile
  }); // close request
}); // close getWatsonToken

在控制器中:

 firebase.auth().onAuthStateChanged(function(user) { // this runs on login
    if (user) { // user is signed in
      console.log("User signed in!");
      $scope.authData = user;
      firebase.database().ref('userLoginEvent').update({'user': user.uid}); // update Firebase database to trigger Cloud Function to get a new IBM Watson token
    } // end if user is signed in
    else { // User is signed out
      console.log("User signed out.");
    }
  }); // end onAuthStateChanged

浏览云功能,它注入四个节点模块,包括用于发送HTTP请求的request,以及将结果写入文件的fs。然后将触发器设置为更新到firebase数据库中的位置userLoginEvent(我是从控制台创建的)。接下来,HTTP请求已删除。响应(令牌)称为body.app.value('watsonToken','" + body + "');是包裹令牌的角值服务。然后fs将所有这些写入我的项目中的位置。

在AngularJS控制器中,onAuthStateChanged触发用户登录时。然后将user.uid更新到firebase数据库中的位置userLoginEvent,云功能触发了HTTP请求,http请求已输出,并且响应写入为角度服务。

相关内容

  • 没有找到相关文章

最新更新