Simon Breton
Simon Breton

Reputation: 2876

'refreshToken_' error with "promisified" Google Analytics's jwt client

I'm trying to call Google Analytics API within an express/React/d3 project. I'm getting close to make all this work however I still need to deal with async callback on the jwtClient to make the GA API call. As you will see in my code, I'm using a promise with bluebird to deal with my jwtClient however I've got the following error :

Cannot read property 'refreshToken_' of undefined

Since I'm still a beginners and I'm just discovering the concept of promise I would love some help.

Here is my code ;

 var google = require ("googleapis");
    var key = require ('./client_id.json');
    const Promise = require('bluebird');
    var authorizationPromise;

    const VIEW_ID = 'ga:80820965';

    let jwtClient = new google.auth.JWT(
      key.client_email, 
      null,
      key.private_key,
      ['https://www.googleapis.com/auth/analytics.readonly'],
      null
    );

    authorizationPromise = Promise.promisify(jwtClient.authorize)()
    .then(function (err, tokens) {
      if (err) {
        throw new Error(err);
      }

      return google.analytics('v3');
    })
    .catch(function(err) {
      console.log(err);
    });

    var queryData = function() {
      authorizationPromise.then(function(analytics) {
          analytics.data.ga.get({
            'auth': jwtClient,
            'ids': VIEW_ID,
            'metrics': 'ga:uniquePageviews',
            'dimensions': 'ga:pagePath',
            'start-date': '30daysAgo',
            'end-date': 'yesterday',
            'sort': '-ga:uniquePageviews',
            'max-results': 10,
          }, function (err, response) {
            if (err) {
              console.log(err);
              return;
            }
            console.log(JSON.stringify(response, null, 4));
          }); 
      });
    };

    module.exports = {
        queryData
    };

Someone help me to write this code but I don't really understand this tokens variable...

thanks.

Upvotes: 0

Views: 186

Answers (1)

Jay Dee
Jay Dee

Reputation: 91

Try changing

Promise.promisify(jwtClient.authorize)()

to

Promise.promisify(jwtClient.authorize, {context:jwtClient})()

Also, your .then(function(err,token) should be just .then(function(tokens) since the err is handled by the .catch

Upvotes: 1

Related Questions