64 lines
1.8 KiB
TypeScript
64 lines
1.8 KiB
TypeScript
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 {
|
|
clientSecret: string = env.GOOGLE_CLIENT_SECRET;
|
|
clientId: string = env.GOOGLE_CLIENT_ID;
|
|
calenderId: string = env.GOOGLE_CALENDAR_ID;
|
|
calendar: any;
|
|
clientEmail: string = env.GOOGLE_CLIENT_EMAIL;
|
|
googlePrivateKey: string = env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, '\n');
|
|
token: any;
|
|
JWT_client: JWT;
|
|
|
|
async init() {
|
|
console.log("INIT GOOGLE CALENDAR")
|
|
const jwtClient = await this.authorize();
|
|
this.calendar = google.calendar({ version: 'v3', auth: jwtClient });
|
|
console.log("DONE INIT GOOGLE CALENDAR")
|
|
}
|
|
|
|
async authorize() {
|
|
console.log("AUTHORIZE GOOGLE CALENDAR")
|
|
this.JWT_client = new JWT({
|
|
email: this.clientEmail,
|
|
key: this.googlePrivateKey,
|
|
scopes: [
|
|
'https://www.googleapis.com/auth/calendar',
|
|
]
|
|
});
|
|
const { access_token } = await this.JWT_client.authorize();
|
|
this.token = access_token;
|
|
if (!this.token) {
|
|
throw new Error('Failed to connect to google calendar');
|
|
}
|
|
console.log("GOOGLE CALENDAR AUTHORIZED SUCCESSFULLY")
|
|
return this.JWT_client;
|
|
}
|
|
|
|
updateNewEvent(upcomingEvents: GoogleCalendarEvent[]) {
|
|
upcomingEvents.forEach((event: GoogleCalendarEvent) => {
|
|
console.log("UPDATE NEW EVENT", upcomingEvents)
|
|
|
|
const options = {
|
|
auth: this.JWT_client,
|
|
calendarId: this.calenderId,
|
|
resource: event,
|
|
}
|
|
|
|
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');
|
|
});
|
|
})
|
|
|
|
}
|
|
}
|