floriday/floriday.js

76 lines
1.9 KiB
JavaScript

import { checkCon, closeCon } from './models/sequelize.js';
import * as utils from './utils.js';
import moment from 'moment';
import chalk from 'chalk';
// Añade la hora a todos los console.log
console.log = (...args) => console.info(chalk.gray(`[${new moment().format('YYYY-MM-DD hh:mm:ss A')}]`), ...args);
const env = process.env;
class Floriday {
async start() {
try {
await utils.checkConfig();
await utils.requestToken();
if (JSON.parse(env.SYNC_ORGANIZATION)) await utils.syncOrganizations();
if (JSON.parse(env.SYNC_CON)) await utils.syncConnections();
if (JSON.parse(env.SYNC_WAREHOUSE)) await utils.syncWarehouses();
if (JSON.parse(env.SYNC_TRADEITEM)) await utils.syncTradeItems();
} catch (err) {
utils.criticalError(err);
}
}
async tryConn() {
while (true)
try {
utils.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 (!this.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 new Error(err);
}
}
async trunk() {
try{
// ------------------------
await utils.syncOrganizations();
await utils.syncConnections();
await utils.syncSupplyLines();
// ------------------------
} catch (err) {
if (err.name === 'SequelizeConnectionRefusedError') throw err;
utils.criticalError(err);
}
}
async stop() {
this.stopSchedule = false;
await closeCon();
console.warn(chalk.dim('Bye, come back soon 👋'))
}
}
export default Floriday;