const Sequelize = require('sequelize'); const path = require('path'); const readdir = require('fs/promises').readdir; class Database { constructor() { } async initialize() { this.connection = await this.#connect(); this.models = await this.#getModels(); await this.#createTables(); } async #connect() { if (this.connection !== undefined) { return this.connection; } if (config?.database === undefined) { throw new Error('missing database config'); } let connection = new Sequelize(config.database.database, config.database.username, config.database.password, { dialect: config.database.dialect, host: config.database.host, port: config.database.port, storage: config.database.storage, logging: false }); await connection.authenticate(); logger.info('successfully connected to the database'); return connection; } async #getModels() { let modelsDirectory = path.resolve(path.join(__dirname, '../models')); const files = await readdir(modelsDirectory); const models = {}; for (let index = 0; index < files.length; index++) { let modelFile = path.join(modelsDirectory, files[index]); if (path.extname(modelFile) !== '.js') { continue; } const model = require(modelFile); if (model.prototype?.createTable === undefined || model.name === 'Base') { continue; } modelFile = path.basename(modelFile); modelFile = modelFile.substring(0, modelFile.indexOf(path.extname(modelFile))); models[modelFile] = model; } return models; } async #createTables() { if (this.models === undefined || this.models.size === 0) { return; } const models = Object.values(this.models); for (let index = 0; index < models.length; index++) { const model = models[index]; try { const timestamp = new Date().getTime(); await model.prototype.createTable(); logger.debug('creation/alteration of table \'' + model.name + '\' finished after ' + (new Date().getTime() - timestamp) + 'ms'); } catch (err) { logger.error('an error occured creating table \'' + model.name + '\' > ' + err); } } } } module.exports = Database;