Calling a Cloud Function from another Cloud Functi

2020-01-28 08:28发布

问题:

I am using a Cloud Function to call another Cloud Function on the free spark tier.

Is there a special way to call another Cloud Function? Or do you just use a standard http request?

I have tried calling the other function directly like so:

exports.purchaseTicket = functions.https.onRequest((req, res) => {    
  fetch('https://us-central1-functions-****.cloudfunctions.net/validate')
    .then(response => response.json())
    .then(json => res.status(201).json(json))
})

But I get the error

FetchError: request to https://us-central1-functions-****.cloudfunctions.net/validate failed, reason: getaddrinfo ENOTFOUND us-central1-functions-*****.cloudfunctions.net us-central1-functions-*****.cloudfunctions.net:443

Which sounds like firebase is blocking the connection, despite it being a google owned, and therefore it shouldn't be locked

the Spark plan only allows outbound network requests to Google owned services.

How can I make use a Cloud Function to call another Cloud Function?

回答1:

You don't need to go through the trouble of invoking some shared functionality via a whole new HTTPS call. You can simply abstract away the common bits of code into a regular javascript function that gets called by either one. For example, you could modify the template helloWorld function like this:

var functions = require('firebase-functions');

exports.helloWorld = functions.https.onRequest((request, response) => {
  common(response)
})

exports.helloWorld2 = functions.https.onRequest((request, response) => {
  common(response)
})

function common(response) {
  response.send("Hello from a regular old function!");
}

These two functions will do exactly the same thing, but with different endpoints.