import { TransactionConfig } from './Transaction.js' import Logger from '../Logger/Logger.js' import Publisher from '../Publisher/Publisher.js' /** * A type that represents a modified version of the TransactionConfig type, excluding the 'throwOnErrors' and 'syncReturn' properties. */ export type ProcessConfig = Omit /** * Represents a long-running process that executes a given function at a specified interval. */ export default class Process { /** * Private member variable representing the interval value. * @type {number} * @private */ private interval: number /** * A logger object used for logging messages, errors, and other information. * @readonly */ public readonly logger: Logger /** * The publisher of the content. */ public readonly publisher: Publisher /** * A reference to the NodeJS.Timeout object representing the interval timer. */ public timeout!: NodeJS.Timeout /** * Constructs a new instance of the LongRunningProcess class. * @param {ProcessConfig} config - The configuration object for the process. * @param {number} interval - The interval at which the process should run. * @returns None */ constructor(config: ProcessConfig, interval: number) { this.interval = interval this.logger = new Logger(config.logger, 'long-running-process') this.publisher = new Publisher(config.publisher) } /** * Executes the provided execution function at a specified interval. * @param {Function} executionFunc - The function to execute. * @returns None */ public async execute(executionFunc) { this.logger.debug('Starting main process code') //Connect DB // if (this.db) await this.db.connect(); //Program loop this.timeout = setInterval(async () => { await this.iexecute(executionFunc) }, this.interval) } /** * Executes the given execution function asynchronously and handles any exceptions that occur. * @param {Function} executionFunc - The function to execute. * @returns {boolean} - Returns true if the execution failed, false otherwise. */ private async iexecute(executionFunc) { let executionFailed = true //failled til we say no! //safe execution handler try { //start DB transaction // if (this.db) await this.db.beginTransaction(); //Execute await executionFunc(this) //Commit DB // if (this.db) await this.db.commit(); // executionFailed = false } catch (e) { /*EXECUTION FAIL*/ this.logger.error('Exception when executing main process code. Rolling back DB!') this.logger.exception(e) //Rollback DB // if (this.db) await this.db.rollback(); } return executionFailed } }