Snai3i-MarketPlace / backend / src / settings.ts
settings.ts
Raw
import { exitProcess } from "./utils/Process";
import { ExitCodes } from "./config/Errors";
// import { setTimeout } from "timers/promises";
import { log } from "./utils/Function";
import { createPool, PoolOptions } from "mysql2";
import {
  MYSQL_DATABASE,
  MYSQL_HOST,
  MYSQL_PASSWORD,
  MYSQL_USER,
} from "./config/CheckableEnv";

/**
 * The MySQL database connection instance.
 * @type {mysql.Pool}
 */
const poolOptions: PoolOptions = {
  host: MYSQL_HOST,
  user: MYSQL_USER,
  password: MYSQL_PASSWORD,
  database: MYSQL_DATABASE,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
};
export const db = createPool(poolOptions).promise();
db.getConnection()
  .then((connection) => {
    log(`🗄️  ==> '${connection.config.database}' DB is Connected.`);
    connection.release(); // Release the connection
  })
  .catch((err) => {
    exitProcess(ExitCodes.ERROR_DATABASE_CONNECTION, {
      error: err.message,
    });
  });

/**
 * System class for managing application startup and error handling.
 */
export default class System {
  /**
   * ProcessError method for exiting the application after a specified time.
   * @param {number} second - The time in seconds after which the process will be terminated.
   */
  static async ProcessError(second: number) {
    // Timeout exit
    // setTimeout(second * 1000).then(() => {
    //   exitProcess(ExitCodes.ERROR_GENERIC, {
    //     error: 'Manual termination after timeout',
    //   });
    // });
    const delay = (ms: number): Promise<void> => new Promise(resolve => setTimeout(resolve, ms));

    try {
      await delay(second * 1000);
      exitProcess(ExitCodes.ERROR_GENERIC, {
        error: 'Manual termination after timeout',
      });
    } catch (error) {
      console.error('An error occurred:', error);
    }
  }

  /**
   * Start method for initializing the application and dependencies.
   */
  static async Start() {
    await db.getConnection();
  }
}