Adding Events With Google Calendar API and Node.js
Pre-requisites
To begin with, create a Calendar.js file in your project directory and paste the below code.
const {google} = require('googleapis');
class Event {
//This auth object should be passed whenever a new instance of class is created in order to authenticate the requests.
constructor(auth){
this.auth = auth;
this.calendar = google.calendar({version: 'v3', auth});
}
addEvent(summary, description, start_date, end_date){
//This is a standard format for creating calendar events.
let event = {
'summary': summary,
'description': description,
'start': {
'dateTime': start_date, // Format: '2015-05-28T09:00:00-07:00'
'timeZone': 'Asia/Calcutta',
},
'end': {
'dateTime': end_date,
'timeZone': 'Asia/Calcutta',
},
'reminders': {
'useDefault': false,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 15},
],
},
};
//We make a request to Google Calendar API.
this.calendar.events.insert({
auth: this.auth,
calendarId: 'primary',
resource: event,
}, function(err, event) {
if (err) {
console.log('There was an error contacting the Calendar service: ' + err);
return;
}
console.log('Event created: %s', event.htmlLink);
});
}
}
module.exports = Event;Let's go through it step by step.
First, we create a class Event which includes an addEvent function and a constructor. The class is initialized with the auth object which we get on successful authentication of the application (explained here).
The addEvent function takes 4 parameters (all string type) summary, description, start_date, and end_date, which are then added to the event object. This event object format is the same as in the official docs.
The important thing to note here is the time format which is
‘2020-03-16T11:00:00’
2020–03–16 represents the date in YYYY-MM-DD format and 11:00:00 is the time. They are both separated with a ‘T’.
The reminders object has an attribute override that sends the user notifications at the specified minutes before the start of the event.
Now we send a request to the Calendar API appending the event object to insert the event in the user’s calendar.
Create an instance of the Event class and call the addEvent function
let event = new Event(auth);
event.addEvent('Summary','Description','2020-03-16T11:00:00','2020-03-18T11:00:00');If the request is successful an event will be created which will be visible in the user’s calendar dashboard.