google calendar | Correct calendar dates for timeMax and timeMin | days events | Search

The correctCalendarId function determines the appropriate Google Calendar to use based on a provided calendarId, handling cases where the ID is undefined, "primary", or needs to be resolved from a list of available calendars. It fetches the calendar list if necessary, selects a matching calendar, and returns the modified options object with the correct calendar ID.

Run example

npm run import -- "Lookup calendar id by name or id"

Lookup calendar id by name or id

var importer = require('../Core');
var authorizeCalendar = importer.import("authorize google calendar");
var assert = require('assert');
var util = require('util');

var calendarList = [], lastCalendar;

function filterCalendar(options) {
    var rexexp = new RegExp(options.calendarId, 'ig');
    var matches = calendarList
        .filter(c => c.id == options.calendarId);
    if (matches.length == 0) {
        matches = calendarList
            .filter(c => c.summary.match(rexexp));
    }
    assert(matches.length > 0, 'something is seriously wrong with the calendarId ' + JSON.stringify(options, null, 4) + JSON.stringify(calendarList, null, 4));
    if (lastCalendar !== matches[0].summary) {
        lastCalendar = matches[0].summary;
        console.log('Using calendar: ' + matches[0].summary
            + ' - ' + matches[0].id);
    }
    options.calendarId = matches[0].id;
    return Promise.resolve(options);
}

function correctCalendarId(options) {
    if (typeof options.calendarId === 'undefined' || options.calendarId === 'primary') {
        return Promise.resolve(Object.assign(options, {
            calendarId: 'primary'
        }))
    }
    if (calendarList.length > 0) {
        return filterCalendar(options);
    }
    return (calendarList.length == 0
        ? authorizeCalendar()
            .then(calendar => util.promisify(calendar.calendarList.list.bind(calendar))())
        : Promise.resolve(calendarList))
        .then(r => {
            calendarList = (r.data || {}).items || [];
            return filterCalendar(options);
        })
        .catch(e => console.log(e))
};

module.exports = correctCalendarId;

What the code could have been:

const { google } = require('googleapis');
const { authorizeGoogleCalendar } = require('../Core');
const { assert } = require('assert');
const console = require('console');

const calendarList = [];
let lastCalendar;

/**
 * Filter calendars based on the provided options.
 * If no exact match is found, search for a calendar with a matching summary.
 * @param {object} options - Options containing calendarId or calendarSummary.
 * @returns {Promise<object>} Resolved options with the matched calendarId.
 */
function filterCalendar(options) {
    return new Promise((resolve, reject) => {
        const regex = new RegExp(options.calendarId, 'ig');
        const exactMatch = calendarList.find((c) => c.id === options.calendarId);

        if (!exactMatch) {
            const summaryMatch = calendarList.find((c) => c.summary.match(regex));
            assert(summaryMatch, `No calendar found for ${JSON.stringify(options, null, 4)} and ${JSON.stringify(calendarList, null, 4)}`);
        } else {
            assert(exactMatch, `No calendar found for ${JSON.stringify(options, null, 4)} and ${JSON.stringify(calendarList, null, 4)}`);
        }

        const selectedCalendar = calendarList.find((c) => c.summary === lastCalendar || c.id === exactMatch.id);
        if (lastCalendar!== selectedCalendar.summary) {
            console.log(`Using calendar: ${selectedCalendar.summary} - ${selectedCalendar.id}`);
            lastCalendar = selectedCalendar.summary;
        }

        options.calendarId = selectedCalendar.id;
        resolve(options);
    });
}

/**
 * Get the correct calendarId based on the provided options.
 * If the calendarId is not provided or is 'primary', use the primary calendar.
 * Otherwise, filter calendars to find the matching calendar.
 * @param {object} options - Options containing calendarId or calendarSummary.
 * @returns {Promise<object>} Resolved options with the matched calendarId.
 */
function correctCalendarId(options) {
    if (options.calendarId === 'primary' ||!options.calendarId) {
        return Promise.resolve({...options, calendarId: 'primary' });
    }

    if (calendarList.length === 0) {
        return authorizeGoogleCalendar()
           .then((calendar) => calendar.calendarList.list().asPromise())
           .then((response) => {
                calendarList = response.data.items || [];
                return filterCalendar(options);
            })
           .catch((error) => {
                console.error(error);
                throw error;
            });
    }

    return filterCalendar(options)
       .catch((error) => {
            console.error(error);
            throw error;
        });
}

module.exports = correctCalendarId;

This code defines a function correctCalendarId that handles the process of selecting a Google Calendar to use based on a provided calendarId.

Here's a breakdown:

  1. Imports:

  2. Variables:

  3. filterCalendar Function:

  4. correctCalendarId Function:

  5. Export: