google scheduling | calendar search heatmap | Cell 7 | Search

This code searches a Google Calendar for events matching given keywords and logs the summaries of the found events. It then sends the results (or any errors) to an external system for further processing.

Run example

npm run import -- "search calendar"

search calendar

var importer = require('../Core');
var {
    getOauthClient,
    listEvents,
    correctCalendarId,
} = importer.import("import google calendar api",
"list events",
"lookup calendar name");

var options = {
    
}

function searchCalendar(search, calendar) {
    if(calendar) {
        options.calendarId = calendar;
    }
    var total = 0;
    return getOauthClient(options)
        .then(() => correctCalendarId(options))
        .then(() => importer.runAllPromises(search.split('|').map(term => resolve => {
            return listEvents({
                auth: options.auth,
                calendarId: options.calendarId,
                q: term
            }).then(r => {
                console.log(term);
                console.log(r.map(e => e.event.summary).slice(0, 10));
                return resolve(r);
            })
        })))
}
module.exports = searchCalendar;

if(typeof $ !== 'undefined') {
    $.async();
    searchCalendar('blur')
        .then(r => $.sendResult(r))
        .catch(e => $.sendError(e))
}

What the code could have been:

const { getOauthClient, listEvents, correctCalendarId } = require('../Core');

const searchCalendar = (search, calendar = null) => {
  const options = { calendarId: calendar };

  return Promise.resolve()
   .then(() => getOauthClient(options))
   .then(() => correctCalendarId(options))
   .then(() => {
      const promises = search.split('|').map(term => listEvents({
        auth: options.auth,
        calendarId: options.calendarId,
        q: term
      }));
      return Promise.all(promises);
    })
   .then(events => {
      console.log('Search results:');
      console.log(events.map(e => e.event.summary).slice(0, 10));
      return events;
    })
   .catch(error => {
      console.error('Error:', error);
      throw error;
    });
};

module.exports = searchCalendar;

// TODO: Refactor this block to remove global variables and improve maintainability
if (typeof $!== 'undefined') {
  $.async();
  searchCalendar('blur')
   .then(result => $.sendResult(result))
   .catch(error => $.sendError(error));
}

This code snippet fetches events from a Google Calendar based on keywords and logs event summaries.

Here's a breakdown:

  1. Dependencies: It imports functions for interacting with the Google Calendar API, including authentication, listing events, and handling calendar IDs.

  2. Configuration: It sets up options for interacting with the Google Calendar, including the calendar ID.

  3. searchCalendar Function:

  4. Execution: