kannon/classes/Database.js

75 lines
2.5 KiB
JavaScript
Raw Permalink Normal View History

2022-04-14 14:23:41 +02:00
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);
2022-06-03 17:04:44 +02:00
if (model.prototype?.createTable === undefined || model.name === 'Base') {
2022-04-14 14:23:41 +02:00
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();
2022-06-03 17:04:44 +02:00
await model.prototype.createTable();
logger.debug('creation/alteration of table \'' + model.name + '\' finished after ' + (new Date().getTime() - timestamp) + 'ms');
2022-04-14 14:23:41 +02:00
} catch (err) {
2022-06-03 17:04:44 +02:00
logger.error('an error occured creating table \'' + model.name + '\' > ' + err);
2022-04-14 14:23:41 +02:00
}
}
}
}
module.exports = Database;