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 { client_secret: string; client_id: string; calender_id: string; calendar: any; clientEmail: string; googlePrivateKey: string; token: any; constructor() { this.client_secret = env.GOOGLE_CLIENT_SECRET; this.client_id = env.GOOGLE_CLIENT_ID; this.calender_id = env.GOOGLE_CALENDAR_ID; this.clientEmail = env.GOOGLE_CLIENT_EMAIL this.googlePrivateKey = env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, '\n'); // this.redirect_uris = env.GOOGLE_REDIRECT_URIS; } async init() { const jwtClient = await this.authorize(); this.calendar = google.calendar({ version: 'v3', auth: jwtClient }); } async authorize() { const client = new JWT({ email: this.clientEmail, key: this.googlePrivateKey, scopes: 'https://www.googleapis.com/auth/calendar.events' }); const { access_token } = await client.authorize(); this.token = access_token; if(!this.token) { throw new Error('Failed to connect to google calendar'); } return client; } updateNewEvent(upcomingEvents: GoogleCalendarEvent[]) { this.calendar.event.insert({ auth: this.token, calendarId: this.calender_id, resource: upcomingEvents[0], }, function (err: any, event: any) { if (err) { console.log('There was an error contacting the Calendar service: ' + err); return; } console.log('Event created: %s', event.htmlLink); }); } }