Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cannot set property 'jwtClient' of undefined" Trying to use Node.js with Google Sheets

I've been following this tutorial : https://www.youtube.com/watch?v=UGN6EUi4Yio I had to stop at 3:43 because of this problem :

Here is the main JS File to get into the Google Spreadsheet :

const GoogleSpreadsheet = require('google-spreadsheet');
const { promisify } = require('util');
const { google } = require('googleapis');


const creds = require('./client_secret');

async function accessSpreadsheet()
{
    const doc = new GoogleSpreadsheet.GoogleSpreadsheet('1i1uSTZ5GkMJFqUGpxsvCOIOZJ6POPOuS9Vu0kDP1y_w');

    await promisify(doc.useServiceAccountAuth)(creds);
    const info = await promisify(doc.getInfo)();
    const sheet = info.worksheets[0];
    console.log(`TItle : ${sheet.title}, Rows: ${sheet.rowCount}`);
}

accessSpreadsheet();

When I execute this, it gives me this error :

TypeError: Cannot set property 'jwtClient' of undefined
at useServiceAccountAuth (C:\Users\Web\WebstormProjects\discordjs\node_modules\google-spreadsheet\lib\GoogleSpreadsheet.js:53:20)"

So I went exploring to find the function. Here is GoogleSpreadsheet.js with the intended function at the end of this code block (rest of the class is removed) :

const _ = require('lodash');
const { JWT } = require('google-auth-library');
const Axios = require('axios');

const GoogleSpreadsheetWorksheet = require('./GoogleSpreadsheetWorksheet');
const { getFieldMask } = require('./utils');

const GOOGLE_AUTH_SCOPES = [
  'https://www.googleapis.com/auth/spreadsheets',

  // the list from the sheets v4 auth for spreadsheets.get
  // 'https://www.googleapis.com/auth/drive',
  // 'https://www.googleapis.com/auth/drive.readonly',
  // 'https://www.googleapis.com/auth/drive.file',
  // 'https://www.googleapis.com/auth/spreadsheets',
  // 'https://www.googleapis.com/auth/spreadsheets.readonly',
];

const AUTH_MODES = {
  JWT: 'JWT',
  API_KEY: 'API_KEY',
};

class GoogleSpreadsheet {
  constructor(sheetId) {
    this.spreadsheetId = sheetId;
    this.authMode = null;
    this._rawSheets = {};
    this._rawProperties = null;

    // create an axios instance with sheet root URL and interceptors to handle auth
    this.axios = Axios.create({
      baseURL: `https://sheets.googleapis.com/v4/spreadsheets/${sheetId}`,
    });
    // have to use bind here or the functions dont have access to `this` :(
    this.axios.interceptors.request.use(this._setAxiosRequestAuth.bind(this));
    this.axios.interceptors.response.use(
      this._handleAxiosResponse.bind(this),
      this._handleAxiosErrors.bind(this)
    );

    return this;
  }

  // AUTH RELATED FUNCTIONS ////////////////////////////////////////////////////////////////////////
  async useApiKey(key) {
    this.authMode = AUTH_MODES.API_KEY;
    this.apiKey = key;
  }

  // creds should be an object obtained by loading the json file google gives you
  async useServiceAccountAuth(creds) {
    this.jwtClient = new JWT({
      email: creds.client_email,
      key: creds.private_key,
      scopes: GOOGLE_AUTH_SCOPES,
    });
    await this.renewJwtAuth();
  }

The creds file info (parameter) seems to output fine using a console.log.

I am a beginner in JavaScript and have read how to initialize those properties, with no luck. GoogleSpreadsheet.js is not my code.

like image 931
FGuindon Avatar asked Feb 22 '20 04:02

FGuindon


1 Answers

It seems that the node_module 'google-spreadsheets' has released a new version.

I was able to get past the above error with this mashup of the module documentation and the video from Twilio.

const { GoogleSpreadsheet } = require('google-spreadsheet');
const creds = require('./credentials.json');

// spreadsheet key is the long id in the sheets URL
const doc = new GoogleSpreadsheet('1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms');

async function accessSpreadsheet() {
  await doc.useServiceAccountAuth({
    client_email: creds.client_email,
    private_key: creds.private_key,
  });

  await doc.loadInfo(); // loads document properties and worksheets
  console.log(doc.title);

  const sheet = doc.sheetsByIndex[0]; // or use doc.sheetsById[id]
  console.log(sheet.title);
  console.log(sheet.rowCount);

}

accessSpreadsheet();
like image 170
codeangler Avatar answered Oct 01 '22 17:10

codeangler