Calling a Cloud Function from another Cloud Function

前端 未结 4 2200
时光取名叫无心
时光取名叫无心 2020-11-27 18:58

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 standa

4条回答
  •  [愿得一人]
    2020-11-27 19:20

    It's possible to invoke another Google Cloud Function over HTTP by including an authorization token. It requires a primary HTTP request to calculate the token, which you then use when you call the actual Google Cloud Function that you want to run.

    https://cloud.google.com/functions/docs/securing/authenticating#function-to-function

    const {get} = require('axios');
    
    // TODO(developer): set these values
    const REGION = 'us-central1';
    const PROJECT_ID = 'my-project-id';
    const RECEIVING_FUNCTION = 'myFunction';
    
    // Constants for setting up metadata server request
    // See https://cloud.google.com/compute/docs/instances/verifying-instance-identity#request_signature
    const functionURL = `https://${REGION}-${PROJECT_ID}.cloudfunctions.net/${RECEIVING_FUNCTION}`;
    const metadataServerURL =
      'http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=';
    const tokenUrl = metadataServerURL + functionURL;
    
    exports.callingFunction = async (req, res) => {
      // Fetch the token
      const tokenResponse = await get(tokenUrl, {
        headers: {
          'Metadata-Flavor': 'Google',
        },
      });
      const token = tokenResponse.data;
    
      // Provide the token in the request to the receiving function
      try {
        const functionResponse = await get(functionURL, {
          headers: {Authorization: `bearer ${token}`},
        });
        res.status(200).send(functionResponse.data);
      } catch (err) {
        console.error(err);
        res.status(500).send('An error occurred! See logs for more details.');
      }
    };
    

提交回复
热议问题