floriday/floriday.js

75 lines
1.8 KiB
JavaScript

import { models, checkConn, closeConn } 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();
this.tokenExpirationDate = await utils.requestToken(models);
if (JSON.parse(env.SYNC_SEQUENCE)) await utils.syncSequence();
if (JSON.parse(env.SYNC_SUPPLIER)) await utils.syncSuppliers();
if (JSON.parse(env.SYNC_CONN)) await utils.syncConn();
if (JSON.parse(env.SYNC_TRADEITEM)) await utils.syncTradeItems();
} catch (err) {
utils.criticalError(err);
}
await this.schedule();
}
async tryConn() {
try {
utils.sleep(env.DB_TIMEOUT_RECONECT);
await checkConn();
await this.schedule();
}
catch (err) {
throw new Error(err);
}
}
async schedule () {
try {
const intervalTime = JSON.parse(env.IS_PRODUCTION)
? env.MS_PRODUCTION_SCHEDULE
: env.MS_TEST_SCHEDULE;
while (true) {
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{
if (moment().isAfter(await utils.getCurrentTokenExpiration())) {
this.tokenExpirationDate = await utils.requestToken(models);
}
await utils.syncSupplyLines();
// Continuar con todo lo que haga falta realizar en la rutina
} catch (err) {
utils.criticalError(err);
}
}
async stop() {
await closeConn();
console.log(chalk.dim('Bye, come back soon 👋'))
}
}
export default Floriday;