haifa-reminder/src/GoogleCalendar.ts

65 lines
1.8 KiB
TypeScript
Raw Normal View History

import { JWT } from 'google-auth-library';
import { google } from 'googleapis';
import { GoogleCalendarEvent } from './types/index';
require('dotenv').config();
const env = process.env;
export default class GoogleCalendar {
2023-03-22 14:19:53 +00:00
clientSecret: string = env.GOOGLE_CLIENT_SECRET;
clientId: string = env.GOOGLE_CLIENT_ID;
calenderId: string = env.GOOGLE_CALENDAR_ID;
calendar: any;
2023-03-22 14:19:53 +00:00
clientEmail: string = env.GOOGLE_CLIENT_EMAIL;
googlePrivateKey: string = env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, '\n');
token: any;
2023-03-22 14:19:53 +00:00
JWT_client: JWT;
async init() {
2023-03-22 14:19:53 +00:00
console.log("INIT GOOGLE CALENDAR")
const jwtClient = await this.authorize();
this.calendar = google.calendar({ version: 'v3', auth: jwtClient });
2023-03-22 14:19:53 +00:00
console.log("DONE INIT GOOGLE CALENDAR")
}
async authorize() {
2023-03-22 14:19:53 +00:00
console.log("AUTHORIZE GOOGLE CALENDAR")
this.JWT_client = new JWT({
email: this.clientEmail,
key: this.googlePrivateKey,
2023-03-22 14:19:53 +00:00
scopes: [
'https://www.googleapis.com/auth/calendar',
]
});
2023-03-22 14:19:53 +00:00
const { access_token } = await this.JWT_client.authorize();
this.token = access_token;
2023-03-22 14:19:53 +00:00
if (!this.token) {
throw new Error('Failed to connect to google calendar');
}
2023-03-22 14:19:53 +00:00
console.log("GOOGLE CALENDAR AUTHORIZED SUCCESSFULLY")
return this.JWT_client;
}
updateNewEvent(upcomingEvents: GoogleCalendarEvent[]) {
2023-03-22 14:19:53 +00:00
upcomingEvents.forEach((event: GoogleCalendarEvent) => {
console.log("UPDATE NEW EVENT", upcomingEvents)
const options = {
auth: this.JWT_client,
calendarId: this.calenderId,
resource: event,
}
2023-03-22 14:19:53 +00:00
this.calendar.events.insert(options, function (err: any, event: any) {
if (err) {
console.log('There was an error contacting the Calendar service: ' + err);
return;
}
console.log(event.description + ' created');
});
})
}
}