Search code examples
node.jsgoogle-cloud-functionsgoogle-api-nodejs-client

cloud function and jwt Google token request


I know that I should use the cloud function service account to access to my bigquery but for my specific needs I want to have the choice of my service account.

So I decided to generate a token and use this token with the Google JWT client. The code (I retrieed in the Google example library) is working perfectly in local but when I try to deploy gcloud raises an error. I don't understand why and I don't know what way to explore to solve that.

const {JWT} = require('google-auth-library');
exports.getGoogleToken = (req,res) => {
    const client = new JWT(
    key.client_email,
    null,
    key.private_key,
    ['https://www.googleapis.com/auth/cloud-platform','https://www.googleapis.com/auth/bigquery','https://www.googleapis.com/auth/bigquery.insertdata']
  );
  await client.authorize();
  const url = `https://www.googleapis.com/bigquery/v2/projects`;
  const response = await client.request({url});
  authorization=response.config.headers.Authorization;
  res.status(200).send(authorization);
}

To deploy the function I use this syntax :

gcloud functions deploy getGoogleToken --region=europe-west1 --memory=128MB --trigger-http --timeout=60

And I get this error :

**ERROR**: (gcloud.functions.deploy) OperationError: code=3, message=Function 
load error: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: /user_code/index.js:32
await client.authorize();
      ^^^^^^

SyntaxError: Unexpected identifier
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:549:28)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
    at getUserFunction (/var/tmp/worker/worker.js:388:24)

I suppose the library is not supported by Google cloud functions but it's a Google library?

Could someone help me please ?

Have a great day


Solution

  • My bad sorry, but if someone is asking the same question just read that.

    For the moment cloud function is working with nodejs Version 6 and this code is using await/async requires higher version of nodejs. You can solve this problem by using beta (Be carefull beta means there is no garantee and no SLA)

    the deployment syntax is this one :

    gcloud beta functions deploy [functionName] --runtime nodejs8
    

    Replace [functionName] by your function name. Note the word "beta" in the second place of the syntax.