If you are looking to access free slots on your Google Calendar, it can be done in just two simple steps. Utilizing npm google-calendar
Firstly, retrieve all the free/busy time slots from your calendar.
var startDateTime = new Date(),
endDateTime = new Date();
var rootStartTime = startDateTime,
rootEndTime = endDateTime;
gcal(<accessToken>).freebusy.query({
"items":[{
"id": calendarObjectName.name
}],
"timeMin": startDateTime.toISOString(),
"timeMax": endDateTime.toISOString(),
"timeZone": "GMT+0100"
},{
fields: "calendars,groups,kind,timeMax,timeMin",
alt:"json"
}, function(err, responseData) {
if(err) return console.log(err)
// further process and identify free slots
return determineSlotsFromEvents(startDateTime, responseData.calendars[<calendarName>].busy)
})
var interval = 2, // duration of a single slot (in this case, set to 2 hours)
freeSlotsArr = [];
function determineSlotsFromEvents(dateTime, eventsData) {
eventsData.forEach(function (singleEvent, index) { //calculate free slots based on busy times
if (index == 0 && startDateTime < singleEvent.start) {
freeSlotsArr.push({startDateTime: startDateTime, endDateTime: singleEvent.start});
}
else if (index == 0) {
startDateTime = singleEvent.end;
}
else if (eventsData[index - 1].end < singleEvent.start) {
freeSlotsArr.push({startDateTime: eventsData[index - 1].end, endDateTime: singleEvent.start});
}
if (eventsData.length == (index + 1) && singleEvent.end < endDateTime) {
freeSlotsArr.push({startDateTime: singleEvent.end, endDateTime: endDateTime});
}
});
if (eventsData.length == 0) {
freeSlotsArr.push({startDateTime: startDateTime, endDateTime: endDateTime});
}
var tempObj = {}, hourBasedSlots = [];
freeSlotsArr.forEach(function(freeTimeSlot, index) {
var numHourDiff = new Date(freeTimeSlot.endDateTime).getHours() - new Date(freeTimeSlot.startDateTime).getHours(), startTime = new Date(freeTimeSlot.startDateTime), endTime = new Date(freeTimeSlot.endDateTime);
while(startTime.getHours() + numHourDiff + interval >= 0) { // 11 + 4 + 2 >= 0
if(numHourDiff >= interval) {
tempObj.e = new Date(freeTimeSlot.startDateTime);
tempObj.e.setHours(tempObj.e.getHours() + numHourDiff);
tempObj.s = new Date(freeTimeSlot.startDateTime);
tempObj.s.setHours(tempObj.s.getHours() + numHourDiff - interval);
if(tempObj.s.getHours() >= rootStartTime.getHours() && tempObj.e.getHours() <= rootEndTime.getHours()) {
hourBasedSlots.push({calendarName: calendarObjectName.name, startDateTime:tempObj.s, endDateTime:tempObj.e});
tempObj = {};
}
}
numHourDiff--;
}
})
// callBack(freeSlotsArr, hourBasedSlots);
}