Что я делаю неправильно, когда мне нужно присвоить значение свойству класса в TypeScript, но я получаю сообщение об ошибке: ERROR : uncaughtException: Cannot set property 'auth' of undefined
Мне нужно свойство auth
, который изначально не содержит никакой информации (1) для хранения информации, которую я назначаю в моем методе done
. Но всякий раз, когда я хочу присвоить какое-либо значение этому свойству, оно не работает в моем случае. Я проверял много раз и метод auth в done не является неопределенным. Он содержит информацию, которая передается ему, но в любом случае появляется ошибка.
Setters
и Getters
тоже не помогают.
Если бы мне нужно было присвоить это значение в Angular, это определенно сработало бы, но я предполагаю, что в использовании Class есть небольшая разница.
import fs from 'fs';
import readline from "readline";
import { google } from "googleapis";
import path from 'path';
import { logger } from './winston';
class connectGoogleAPI {
private SCOPES = [
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/gmail.modify',
'https://www.googleapis.com/auth/gmail.compose',
'https://www.googleapis.com/auth/gmail.send'
];
private readonly token_path = path.join(process.cwd(), 'token.json');
private readonly credential_path = path.join(process.cwd(), 'credentials.json');
private auth: any = 'value from auth';
set _auth(auth: any) {
this.auth = auth;
}
get _auth(): any {
return this.auth;
}
constructor() {
}
private done(_a: any) {
this.auth = _a;
// this.auth = (_a as object);
// console.log('done');
}
connect() {
// console.log('connect');
// Load client secrets from a local file.
fs.readFile(this.credential_path, { encoding: 'utf-8' }, (err: any, content: any) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Gmail API.
this.authorize(JSON.parse(content), this.done);
// authorize(JSON.parse(content), listLabels);
});
}
private authorize(credentials: any, callback: any) {
// console.log('authorize');
const { client_secret, client_id, redirect_uris } = credentials.web;
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
fs.readFile(this.token_path, { encoding: 'utf-8' }, (err: any, token: any) => {
if (err) return this.getNewToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
logger.info(`Connected to Google API successfully`);
callback(oAuth2Client);
});
}
private getNewToken(oAuth2Client: any, callback: any) {
// console.log('getNewToken');
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: this.SCOPES,
});
logger.warn('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code: any) => {
rl.close();
oAuth2Client.getToken(code, (err: any, token: any) => {
if (err) return logger.error('Error retrieving access token', err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(this.token_path, JSON.stringify(token), (err: any) => {
if (err) return console.error(err);
logger.info('Token stored to', this.token_path);
});
return callback(oAuth2Client);
});
});
}
getAuth() {
if (this.auth === null || this.auth === undefined) {
logger.warn('Getting again auth - Google API');
this.connect();
}
return this.auth;
}
}
export const googleAPI = new connectGoogleAPI();
Буду признателен за любую помощь и советы.
1. Я уже пытался присвоить некоторую информацию в конструкторе, чтобы она не была пустой, но она также работала