jazzgil
jazzgil

Reputation: 2366

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

I'm trying to issue a request to my cloud endpoint project when a certain value is written in the firebase database. I can't find any example of how perform a request to Endpoints in Node.js. Here's what I come up with so far:

"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);
       });
});

When triggered, Functions' log spouts: TypeError: Cannot read property 'init' of undefined. i.e. doesn't even recognize gapi.client.

First, what is the right package to use for this request? googleapis? request-promise?

Second, am I setting up the correct path and parameters for a call to an endpoint? Assume the endpoint function is startCalc(int uid).

Upvotes: 5

Views: 2419

Answers (1)

jazzgil
jazzgil

Reputation: 2366

Update

It seems that Cloud Functions for Firebase blocks requests to their App Engine service - at least on the Spark plan (even though they're both owned by Google - so you'd assume "on the same network"). 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 accessing Google API when you perform a request to your server running on Google's App Engine.

Can't explain why Firebase advocates here steer clear of this question like from fire.

Original Answer

Figured it out - switched to 'request-promise' library:

"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);
    });
});

Upvotes: 7

Related Questions