floriday/floriday.js

79 lines
1.9 KiB
JavaScript

import { checkCon, closeCon } from './models/sequelize.js';
import * as utils from './utils.js';
import chalk from 'chalk';
import yml from 'js-yaml';
import fs from 'fs';
const env = process.env;
const flModels = yml.load(fs.readFileSync('./models/models.yml', 'utf8'));
let cycle = 1, stopSchedule = false;
class Floriday {
async start() {
try {
await utils.checkConfig();
await utils.checkToken();
await utils.separator('Init');
} catch (err) {
utils.handler('critical', err);
}
};
async tryConn() {
while (true)
try {
await utils.handler('warning', new Error('Awaiting a response from the database...'));
await utils.sleep(env.DB_RECON_TIMEOUT);
await checkCon();
await this.schedule();
}
catch (err) {};
};
async schedule () {
try {
const intervalTime = JSON.parse(env.IS_PRODUCTION)
? env.MS_PRODUCTION_SCHEDULE
: env.MS_TEST_SCHEDULE;
while (!stopSchedule) {
try {
await this.trunk();
await new Promise(resolve => setTimeout(resolve, intervalTime));
} catch (err) {
await this.tryConn();
await new Promise(resolve => setTimeout(resolve, intervalTime));
}
}
} catch (err) {
throw err;
};
};
async trunk() {
try{
await utils.checkConnections();
for (let model of flModels) {
if (stopSchedule) return;
await utils.syncModel(model);
}
await utils.separator(`${cycle++} ${(cycle == 2 ? 'Cycle' : 'Cycles')}`);
} catch (err) {
if (includes('ER_SOCKET_UNEXPECTED_CLOSE','ECONNREFUSED').includes(err?.original?.code) || (err?.message).substring(0, 24) === 'SequelizeConnectionError')
throw err;
utils.handler('critical', err);
}
};
async stop() {
try {
stopSchedule = true;
await closeCon();
console.warn(chalk.dim('\nBye, come back soon 👋'))
} catch (err) {
utils.handler('critical', err);
}
};
};
export default Floriday;