Andy Cooper
Andy Cooper

Reputation: 79

Cloud Function: TypeError: Cannot read property 'auth' of undefined

I am using Google Cloud Functions and wrote a function in the console. But I keep getting this error:

TypeError: Cannot read property 'auth' of undefined

Here is my index.js

var {google} = require('googleapis');
const { auth } = require('google-auth-library');

exports.goWithTheDataFlow  = (event, callback) => {


const file = event.data;
  const context = event.context;

  console.log(`Event ${context.eventId}`);
  console.log(`  Event Type: ${context.eventType}`);
  console.log(`  Bucket: ${file.bucket}`);
  console.log(`  File: ${file.name}`);
  console.log(`  Metageneration: ${file.metageneration}`);
  console.log(`  Created: ${file.timeCreated}`);
  console.log(`  Updated: ${file.updated}`);

  google.auth.getApplicationDefault(function (err, authClient, projectId) {
     if (err) {
       throw err;
     }

 console.log(projectId);

 const dataflow = google.dataflow({ version: 'v1b3', auth: authClient });
        console.log(`gs://${file.bucket}/${file.name}`);
 dataflow.projects.templates.create({
   projectId: projectId,
   resource: {
     parameters: {
       inputFile: `gs://${file.bucket}/${file.name}`

     },
     jobName: 'cloud-fn-beam-test',
     gcsPath: 'gs://goldsgymdemo/templates/MyGCStoBQDFTemplate'
   }
 }, function(err, response) {
   if (err) {
     console.error("problem running dataflow template, error was: ", err);
   }
   console.log("Dataflow template response: ", response);
   callback();
 });

   });

 callback();
};

Here is my package.json.

{
  "name": "sample-cloud-storage",
  "version": "0.0.1",
    "dependencies": {
    "googleapis": "^21.3.0",
    "google-auth-library":  "^1.6.0" 
  }
}

I have created this function directly in the Google Cloud Functions Console UI. I am trying to follow the example here but I believe this was built locally. Whereas I am trying to use the Google Cloud Functions Console UI directly instead. Because I am already in GCP and writing this function in the Console UI - do I need to authenticate? Shouldn't it pick up the user credentials & project id directly?

Cloud Functions: Detailed stack trace: Error: Cannot find module 'googleapis'

Thanks!

Upvotes: 1

Views: 5569

Answers (1)

Federico Panunzio
Federico Panunzio

Reputation: 964

I just made a quick test and was able to make it work by using

const google = require('googleapis'); 

and deleting

const { auth } = require('google-auth-library');

Also, I used the following package.json

{
  "name": "sample-cloud-storage",
  "version": "0.0.1",
  "dependencies": {
    "googleapis": "24.0.0"
  }
}

Upvotes: 4

Related Questions