From 9b5922b2417af80e59e5ee8badd23e93d27fde96 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 15 Jun 2023 12:50:58 +0200 Subject: [PATCH] refs #4823 Minor changes --- .env_template | 1 + floriday.js | 5 ++- utils.js | 99 ++++++++++++++++++++++++++++----------------------- 3 files changed, 59 insertions(+), 46 deletions(-) diff --git a/.env_template b/.env_template index 98dccf6..79ecb68 100644 --- a/.env_template +++ b/.env_template @@ -10,6 +10,7 @@ DB_SCHEMA = schema DB_USER = root DB_PWD = root DB_HOST = localhost +DB_PORT = 3306 DB_DIALECT = mariadb DB_RECON_TIMEOUT = 30000 DB_MAX_CONN_POOL = 40 diff --git a/floriday.js b/floriday.js index 0d5f7b3..b6f4663 100644 --- a/floriday.js +++ b/floriday.js @@ -11,7 +11,7 @@ class Floriday { async start() { try { await utils.checkConfig(); - await utils.requestToken(); + await utils.checkToken(); } catch (err) { utils.criticalError(err); } @@ -49,10 +49,13 @@ class Floriday { async trunk() { try{ + /* for (let model of flModels) await utils.syncModel(model); await utils.checkConnections(); + */ + await utils.deleteConnections(); } catch (err) { if (['SequelizeConnectionRefusedError', 'SequelizeConnectionError'].includes(err.name)) throw err; diff --git a/utils.js b/utils.js index 62007da..41d79d1 100644 --- a/utils.js +++ b/utils.js @@ -13,24 +13,25 @@ const flModels = yml.load(fs.readFileSync('./models/models.yml', 'utf8')); let spinner; /** - * Gets the Access Token. + * Check if the token is valid, and if it + * is not, get a new one. * * @param {Boolean} isForce Force to request new token */ -export async function requestToken(isForce = false) { - await startSpin(`Checking token...`, true); - let optionalMsg; +export async function checkToken(isForce) { try { + await startSpin(`Checking token...`, true); + const clientConfigData = await models.config.findOne(); - let tokenExpiration, token; + let tokenExpiration, token, optionalMsg; if (clientConfigData) { token = clientConfigData.currentToken; tokenExpiration = clientConfigData.tokenExpiration; } if (isForce || !token || !tokenExpiration || moment().isAfter(tokenExpiration)) { - await txtSpin(`Requesting new token...`, false); + await txtSpin(`Requesting new token...`); const clientId = JSON.parse(env.USE_SECRETS_DB) ? clientConfigData.clientId || env.CLIENT_ID : env.CLIENT_ID; const clientSecret = JSON.parse(env.USE_SECRETS_DB) ? clientConfigData.clientSecret || env.CLIENT_SECRET : env.CLIENT_SECRET; @@ -41,16 +42,16 @@ export async function requestToken(isForce = false) { scope: 'role:app catalog:read supply:read organization:read network:write network:read' }).toString(); const headers = { 'Content-Type': 'application/x-www-form-urlencoded' }; - const response = (await vnRequest('POST', env.API_ENDPOINT, data, headers)).data; + const res = (await vnRequest('POST', env.API_ENDPOINT, data, headers)).data; const tokenExpiration = moment() - .add(response.expires_in, 's') + .add(res.expires_in, 's') .format('YYYY-MM-DD HH:mm:ss'); await updateClientConfig({ clientId, clientSecret, - currentToken: response.access_token, + currentToken: res.access_token, tokenExpiration, }); } else @@ -134,10 +135,9 @@ export async function sleep(ms) { */ export async function syncModel(model) { await startSpin(`Syncing ${model}...`, true); - let i = 0; try { const dbSeqNum = await models.sequenceNumber.findOne({ where: { model } }) - let curSeqNum = dbSeqNum?.maxSequenceNumber ?? 0; + let curSeqNum = dbSeqNum?.maxSequenceNumber ?? 0, i = 0; if (!flModels.includes(model)) throw new Error('Unsupported model'); @@ -158,7 +158,7 @@ export async function syncModel(model) { const data = res.results; curSeqNum = res.maximumSequenceNumber; misSeqNum = maxSeqNum - curSeqNum; - await insertModel(model, data) + await insertModel(model, data); txtSpin(`Syncing ${i = i + data.length} ${model}, ${misSeqNum} missing...`); await insertSequenceNumber(model, curSeqNum); } @@ -173,29 +173,36 @@ export async function syncModel(model) { }; /** - * Insert a model. + * Insert data to a model. + * + * @param {String} model Supported models (./models/methods.yml) + * @param {Array} data An array containing the data to be inserted */ export async function insertModel(model, data) { - switch (model) { - case 'organizations': - await insertOrganizations(data); - break; - case 'warehouses': - await insertWarehouses(data); - break; - case 'tradeItems': - await insertTradeItems(data); - break; - case 'supplyLines': - await insertSupplyLines(data); - break; - case 'clockPresalesSupply': - await insertClockPresalesSupply(data); - break; - default: - throw new Error('Unsupported model'); + try { + switch (model) { + case 'organizations': + await insertOrganizations(data); + break; + case 'warehouses': + await insertWarehouses(data); + break; + case 'tradeItems': + await insertTradeItems(data); + break; + case 'supplyLines': + await insertSupplyLines(data); + break; + case 'clockPresalesSupply': + await insertClockPresalesSupply(data); + break; + default: + throw new Error('Unsupported model'); + } + } catch (err) { + throw err; } -} +}; /** * Check (create and/or remove) the connections in Floriday. @@ -689,8 +696,11 @@ export async function deleteConnections() { for (let connection of ghostConnections) { await vnRequest('DELETE', `${env.API_URL}/connections/${connection}`); - txtSpin(`Deleting ${i++} connections, ${ghostConnections.length - i} missing...`); + (spinner) + ? txtSpin(`Deleting ${i++} connections, ${ghostConnections.length - i} missing...`) + : startSpin(`Deleting ${i++} connections, ${ghostConnections.length - i} missing...`, true); } + if (spinner) okSpin(null, true); } catch (err) { await criticalSpin(err); } @@ -725,7 +735,7 @@ export async function vnRequest(method, url, data, headers) { case 'EAI_AGAIN': // getaddrinfo await warnSpin(null, err, false); await sleep(1000); - await startSpin(null, false); + await startSpin(null, true); break; case 'ECONNABORTED': case 'ECONNREFUSED': @@ -737,32 +747,32 @@ export async function vnRequest(method, url, data, headers) { case 502: await warnSpin(null, err, false); await sleep(1000); - await startSpin(null, false); + await startSpin(null, true); break; case 429: // Too Many Requests await warnSpin(null, err, false); await sleep(60000); - await startSpin(null, false); + await startSpin(null, true); break; case 401: // Unauthorized await warnSpin(null, err, false); - await requestToken(true); + await checkToken(true); headers.Authorization ? headers.Authorization = `Bearer ${await getCurrentToken()}` : criticalError(err); - await startSpin(null, false); + await startSpin(null, true); break; default: await warnSpin(null, err, false); await sleep(env.MS_RETRY_UNHANDLED_ERROR); - await startSpin(null, false); + await startSpin(null, true); break; } break; default: await warnSpin(null, err, false); await sleep(env.MS_RETRY_UNHANDLED_ERROR); - await startSpin(null, false); + await startSpin(null, true); break; } } @@ -793,7 +803,6 @@ export async function startSpin(msg, isNew) { * Sets the text of spinner. * * @param {String} msg Text of spinner - * @param {Boolean} clear Clean the instance **/ export async function txtSpin(msg) { if (JSON.parse(env.TIME_STAMPS) && msg) @@ -815,7 +824,7 @@ export async function okSpin(msg, clear) { if (spinner) { spinner.succeed(msg); if (clear) - spinner.clear(); + spinner = null; } }; @@ -833,7 +842,7 @@ export async function warnSpin(msg, err, clear) { if (spinner) { spinner.warn(msg); if (clear) - spinner.clear(); + spinner = null; } if (err) await warning(err); }; @@ -848,7 +857,7 @@ export async function failSpin(err, clear) { if (spinner) { spinner.fail(); if (clear) - spinner.clear(); + spinner = null; } if (err) throw err; }; @@ -861,7 +870,7 @@ export async function failSpin(err, clear) { export async function criticalSpin(err) { if (spinner) { spinner.fail(); - spinner.clear(); + spinner = null; } await criticalError(err); };