Cloud Functions for Firebase:如何向我的 Cloud Endpoint 发出请求

Cloud Functions for Firebase: how to issue a request to my Cloud Endpoint

当某个值写入 firebase 数据库时,我正在尝试向我的云端点项目发出请求。我在 Node.js 中找不到任何关于如何向 Endpoints 执行请求的示例。这是我到目前为止的想法:

"use strict";
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const gapi = require('googleapis');

admin.initializeApp(functions.config().firebase);

exports.doCalc = functions.database.ref('/users/{uid}/calc').onWrite(event => {
    return gapi.client.init({
            'apiKey': 'AIzxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
            'clientId': '1234567890-xxx.apps.googleusercontent.com',
            'scope': 'donno what to put here'
       }).then(function() {
           return gapi.client.request({
               'path': 'https://myproj.appspot.com/_ah/api/myApi/v1',
               'params': {'query': 'startCalc', uid: event.params.uid }
           })
       }).then(function(response) {
           console.log(response.result);
       }, function(reason) {
           console.log('Error: ' + reason.result.error.message);
       });
});

触发时,Functions 的日志喷出:TypeError: Cannot read property 'init' of undefined。即甚至不认识 gapi.client.

首先,这个请求应该使用什么包?谷歌API?请求承诺?

其次,我是否为端点调用设置了正确的路径和参数?假设端点函数是 startCalc(int uid)

更新

似乎 Cloud Functions for Firebase 阻止了对其 App Engine 服务的请求 - 至少在 Spark 计划中(即使它们都属于 Google - 所以你会假设“"). The request below, works on a local machine running Node.js, but fails on the Functions server, with a getaddrinfo EAI_AGAIN error, as described here. Evidently, it is not considered 当您在 Google 的 App Engine 上向您的服务器 运行 执行请求时访问 Google API。

无法解释为什么这里的 Firebase 提倡者像远离火一样避开这个问题。

原答案

想通了 - 切换到 'request-promise' 库:

"use strict";
const functions = require('firebase-functions');
const request = require('request-promise');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.doCalc = functions.database.ref('/users/{uid}/calc').onWrite(event => {
    return request({
        url: `https://myproj.appspot.com/_ah/api/myApi/v1/startCalc/${event.params.uid}`,
        method: 'POST'
    }).then(function(resp) {
        console.log(resp);
    }).catch(function(error) {
        console.log(error.message);
    });
});