0

I am working on authorizing a JWT token using the googleapis node package. I am following the example from this link: Here If I change the variable name of the imported package it will yield an error.

Why does example 1 work but example 2 yields below error:

const jwt = new googleapi.auth.JWT(
                        ^
TypeError: Cannot read property 'auth' of undefined

Example 1

'use strict'

const { google } = require('googleapis')

const scopes = 'https://www.googleapis.com/auth/analytics.readonly'
const jwt = new google.auth.JWT(
  process.env.CLIENT_EMAIL,
  null,
  process.env.PRIVATE_KEY,
  scopes
)
const view_id = 'XXXXXXX'

jwt.authorize((err, response) => {
  google.analytics('v3').data.ga.get(
    {
      auth: jwt,
      ids: 'ga:' + view_id,
      'start-date': '30daysAgo',
      'end-date': 'today',
      metrics: 'ga:pageviews'
    },
    (err, result) => {
      console.log(err, result)
    }
  )
})

Example 2

'use strict'

const { googleapi } = require('googleapis')

const scopes = 'https://www.googleapis.com/auth/analytics.readonly'
const jwt = new googleapi.auth.JWT(
  process.env.CLIENT_EMAIL,
  null,
  process.env.PRIVATE_KEY,
  scopes
)
const view_id = 'XXXXXXX'

jwt.authorize((err, response) => {
  googleapi.analytics('v3').data.ga.get(
    {
      auth: jwt,
      ids: 'ga:' + view_id,
      'start-date': '30daysAgo',
      'end-date': 'today',
      metrics: 'ga:pageviews'
    },
    (err, result) => {
      console.log(err, result)
    }
  )
})
lukechambers91
  • 691
  • 1
  • 6
  • 21

1 Answers1

1

This syntax

const { google } = require('googleapis')

is called Object destructuring.

What it actualy does is that it loads the required module and gets google property from that module and assing it to a variable also called google.

It is the same as this:

const google = require('googleapis').google;

So when you do this:

const { googleapi } = require('googleapis')

it is the same as this:

var googleapi = require('googleapis').googleapi;

The thing is that the googleapis module does not export a property called googleapi.

If you really want the name to be googleapi you can do this:

const { googleapi: google } = require('googleapis');

or

const googleapi = require('googleapis').google;

or even this:

const GoogleAPIs = require('googleapis');
const googleapi = GoogleAPIs.google;
Molda
  • 5,619
  • 2
  • 23
  • 39