0

This code is from oauth nodesjs. I want to ask why we are using '{}' around the var google? I also tried using it without '{}' and got error OAuth2 is undefined. i can't understand what is happening here.

var {google} = require('googleapis');
var OAuth2 = google.auth.OAuth2;
Dishank Jindal
  • 73
  • 1
  • 10

2 Answers2

1

According to the Changelog from google-api-nodejs-client, there are some changes from V26.0.0 onwards that you have to implement in your code, precisely the issue you are experiencing is mentioned. I also took a while to figure this one out...

BREAKING CHANGE: This library is now optimized for es6 modules. In previous versions you would import the library like this:

const google = require('googleapis');

In this and future versions, you must use a named import:

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

You may also reference the type to instantiate a new instance:

const {GoogleApis} = require('googleapis');
const google = new GoogleApis();
sashaskull
  • 51
  • 3
1

To add a little to this answer - this is what's called a destructuring assignment. You can read about them here:

http://2ality.com/2015/01/es6-destructuring.html

The code you're looking at here:

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

Is the same as code that looks like this:

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

This is just a convenient shorthand that was added in es6. We made the change in the googleapis package when we moved towards ES modules, which don't play nicely with the export=foo style syntax. Hope this helps!

Justin Beckwith
  • 7,686
  • 1
  • 33
  • 55