Files
adastra_api/src/database/connectDb.js
T

108 lines
4.5 KiB
JavaScript

const chalk = require('chalk');
const mongoose = require('mongoose');
const DB = require('./mysql');
const sequelize = require('./config/sequelize');
const associate = require('./relationships');
const DateUtilities = require('../utils/dateUtilities');
// Connect to the MongoDB database and log a message to the console
const connectMongoDb = async () => {
try {
if (process.env.APP_ENV === 'production') {
await mongoose.connect(process.env.MONGODB_URI);
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.green('MongoDB connection has been established successfully 🟢'));
} else {
mongoose.set('strictQuery', true);
await mongoose.connect(process.env.MONGODB_URI);
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.green('MongoDB connection has been established successfully 🟢'));
mongoose.set('debug', process.env.DEBUG);
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.red('debug :'), chalk.yellow(process.env.DEBUG));
}
} catch (error) {
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.red('Unable to connect to the MongoDB database 🔴'));
console.error('MongoDB connection error:', error);
// Exit the process if the connection is not successful
process.exit(1);
}
};
// Connect to the MySQL database and log a message to the console
const connectMysqlDb = async () => {
try {
await sequelize.authenticate();
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.green('MySQL connection has been established successfully 🟢'));
// Check that required tables exist instead of synchronizing (no auto-create)
const queryInterface = sequelize.getQueryInterface();
let existingTables = [];
try {
existingTables = await queryInterface.showAllTables();
} catch (err) {
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.red('Unable to list tables from MySQL 🔴'));
console.error(err);
// Exit immediately if unable to list tables
process.exit(1);
}
// Build expected table list from models exported in DB
const expectedTables = [];
Object.keys(DB).forEach((key) => {
const model = DB[key];
if (model && typeof model.getTableName === 'function') {
try {
const t = model.getTableName();
const tableName = typeof t === 'string' ? t : t.tableName;
if (tableName) expectedTables.push(tableName);
// eslint-disable-next-line no-unused-vars
} catch (err) {
// ignore
}
}
});
// Normalize table names to strings for comparison
const existingNormalized = existingTables.map(t => (typeof t === 'string' ? t : t.tableName)).map(t => t.toString());
const missing = expectedTables.filter(t => !existingNormalized.includes(t) && !existingNormalized.includes(t.toLowerCase()));
if (missing.length > 0) {
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.red('Database schema validation failed - missing tables:'), chalk.yellow(missing.join(', ')));
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.red('Run migrations to create the schema: npx sequelize-cli db:migrate'));
// Exit immediately if schema is incomplete
process.exit(1);
}
// If all expected tables are present, create associations
associate();
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.green('Database schema validated successfully 🟢'));
} catch (error) {
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.red('Unable to connect to the MySQL database 🔴'));
console.error('MySQL connection error:', error);
// Exit the process if the connection is not successful
process.exit(1);
}
};
// Connect to all database and log a message to the console
const connectAllDb = async () => {
try {
await connectMongoDb();
await connectMysqlDb();
} catch (error) {
console.error('Failed to connect to databases:', error);
process.exit(1);
}
};
module.exports.connectAllDb = connectAllDb;
module.exports.connectMongoDb = connectMongoDb;
module.exports.connectMysqlDb = connectMysqlDb;
module.exports.default = connectAllDb;