heartbeat | heartbeat thump | Cell 2 | Search

This code uses a Google Calendar to trigger the execution of Node.js scripts by parsing event descriptions and extracting parameters to run.

Run example

npm run import -- "run todays heartbeat items"

run todays heartbeat items

var importer = require('../Core');
var {JSDOM} = require('jsdom');
var {
    getOauthClient,
    getDaysEvents,
    thump
} = importer.import("days events",
"import google calendar api",
"heartbeat thump");

var options = {
    calendarId: 'aws'
};

// test Google calendar API?
function runTodaysHeartbeat(calendar, exit) {
    if(calendar) {
        options.calendarId = calendar;
    }
    return (typeof options.auth === 'undefined'
           ? getOauthClient(options)
           : Promise.resolve([]))
        .then(() => getDaysEvents(new Date(), options))
        .then(r => {
            const heartbeat = r.filter(r => r.event.summary === 'heartbeat'
                                       || r.event.summary === 'todays heartbeat items');
        
            try {
                var dom = new JSDOM('<body>' + (heartbeat[0].event.description || '').replace(/<br\/?>/igm, '\n') + '</body>');
                const desc = dom.window.document.body.textContent.split('\n');
                desc.forEach(c => {
                    if(c.trim().length > 0) {
                        const parameters = (/[\{].*[\}]|[\[].*[\]]|(['"]).*\1/igm).exec(c) || ['""'];
                        thump(c.replace(parameters[0], ''), JSON.parse(parameters[0]), false);
                    }
                });
            } catch ( e ) {
                console.log(e);
            }
        
            if(exit !== false) {
                process.exit(0);
            }
        })
}
module.exports = runTodaysHeartbeat;

if(typeof $ !== 'undefined') {
    $.async();
    runTodaysHeartbeat(false, false)
        .then(r => $.sendResult(r))
        .then(e => $.sendError(e))
}

What the code could have been:

// Import required modules and functions
const { JSDOM } = require('jsdom');
const { getOauthClient, getDaysEvents, thump } = require('../Core').import([
    'days events',
    'google calendar api',
    'heartbeat thump'
]);

// Define default options
const DEFAULT_OPTIONS = {
    calendarId: 'aws'
};

// Function to run today's heartbeat
function runTodaysHeartbeat(calendar = null, exit = false) {
    // Update calendar ID if provided
    if (calendar) {
        DEFAULT_OPTIONS.calendarId = calendar;
    }

    // Return a promise chain to handle Google calendar API
    return (typeof DEFAULT_OPTIONS.auth === 'undefined'
          ? getOauthClient(DEFAULT_OPTIONS)
           : Promise.resolve([]))
       .then(() => getDaysEvents(new Date(), DEFAULT_OPTIONS))
       .then((events) => {
            // Filter events for heartbeat and todays heartbeat items
            const heartbeatEvents = events.filter((event) => {
                return event.event.summary === 'heartbeat'
                       || event.event.summary === 'todays heartbeat items';
            });

            try {
                // Create a JSDOM instance from the heartbeat event description
                const dom = new JSDOM(`${(heartbeatEvents[0]?.event.description || '').replace(//igm, '\n')}');
                const desc = dom.window.document.body.textContent.split('\n')
                   .filter((line) => line.trim().length > 0);

                // Process each line in the heartbeat event description
                desc.forEach((line) => {
                    // Extract parameters from the line
                    const parameters = (/[\{].*[\}]|[\[].*[\]]|(['"]).*\1/igm).exec(line) || ['""'];
                    thump(line.replace(parameters[0], ''), JSON.parse(parameters[0]), false);
                });
            } catch (error) {
                // Log any errors that occur during processing
                globalThis.console.error(error);
            }

            // Exit the process if desired
            if (!exit) {
                globalThis.process.exit(0);
            }
        });
}

// Export the runTodaysHeartbeat function
module.exports = runTodaysHeartbeat;

// Check for $ and async functionality
if (typeof globalThis.$!== 'undefined') {
    globalThis.$.async();
    runTodaysHeartbeat(false, false)
       .then((result) => globalThis.$.sendResult(result))
       .then((error) => globalThis.$.sendError(error));
}

This code fetches events from a Google Calendar, parses their descriptions, and executes Node.js scripts based on the extracted parameters.

Here's a breakdown:

  1. Imports:

  2. Configuration:

  3. runTodaysHeartbeat Function:

  4. Module Export and Execution:

In essence, this code acts as a scheduler or trigger for executing Node.js scripts based on events from a Google Calendar.