refs #4823 Improved code

This commit is contained in:
Guillermo Bonet 2023-05-05 11:48:44 +02:00
parent bfe36b1284
commit 1a97f16a11
4 changed files with 92 additions and 88 deletions

View File

@ -10,6 +10,7 @@ class Floriday {
async start() { async start() {
try { try {
this.tokenExpirationDate = await utils.requestToken(models); this.tokenExpirationDate = await utils.requestToken(models);
if (!env.API_KEY) throw new Error(`You haven't provided the API key`)
if (JSON.parse(env.SYNC_SEQUENCE)) await utils.syncSequence(); if (JSON.parse(env.SYNC_SEQUENCE)) await utils.syncSequence();
if (JSON.parse(env.SYNC_SUPPLIER)) await utils.syncSuppliers(); if (JSON.parse(env.SYNC_SUPPLIER)) await utils.syncSuppliers();
if (JSON.parse(env.SYNC_CONN)) await utils.syncConn(); if (JSON.parse(env.SYNC_CONN)) await utils.syncConn();

View File

@ -12,14 +12,11 @@ const clientConfig = {
clientSecret: { clientSecret: {
type: Sequelize.STRING, type: Sequelize.STRING,
}, },
requestLimit: {
type: Sequelize.INTEGER,
},
currentToken: { currentToken: {
type: Sequelize.STRING(2000), type: Sequelize.STRING(2000),
}, },
tokenExpiration: { tokenExpiration: {
type: Sequelize.STRING, type: Sequelize.DATE,
}, },
}; };

View File

@ -2,9 +2,11 @@ import { Sequelize } from 'sequelize';
import dotenv from 'dotenv'; import dotenv from 'dotenv';
import chalk from 'chalk'; import chalk from 'chalk';
import ora from 'ora'; import ora from 'ora';
import { criticalError } from './../utils.js'; import { criticalError, updateClientConfig } from './../utils.js';
dotenv.config(); dotenv.config();
const env = process.env;
console.clear() console.clear()
console.log(chalk.hex('#06c581')( console.log(chalk.hex('#06c581')(
` `
@ -178,17 +180,6 @@ if (JSON.parse(process.env.FORCE_SYNC)) {
const modSpinner = ora(`${action} models...`).start(); const modSpinner = ora(`${action} models...`).start();
try { try {
await sequelize.sync({ force: isForce }); await sequelize.sync({ force: isForce });
if (process.env.SECRETS) {
await models.clientConfig.findOrCreate({
where: {
id: 1,
},
defaults: {
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
},
});
}
modSpinner.succeed(); modSpinner.succeed();
} }
catch (err) { catch (err) {

145
utils.js
View File

@ -13,61 +13,76 @@ const env = process.env;
* @returns {Date} tokenExpirationDate formated as YYYY-MM-DD HH:mm:ss * @returns {Date} tokenExpirationDate formated as YYYY-MM-DD HH:mm:ss
*/ */
export async function requestToken() { export async function requestToken() {
const clientConfigData = await models.clientConfig.findOne(); let spinner;
try {
spinner = ora(`Requesting new token...`).start();
if (!clientConfigData) if (!env.CLIENT_ID || !env.CLIENT_SECRET)
throw new Error('No data found in the client config table') throw new Error(`You haven't provided the credentials`)
const spinner = ora(`Requesting new token...`).start(); const clientConfigData = await models.clientConfig.findOne();
const tokenExpirationDate = clientConfigData.tokenExpiration;
if (clientConfigData.tokenExpiration == null || moment().isAfter(tokenExpirationDate)) { let tokenExpirationDate;
let clientId = clientConfigData.clientId; if (clientConfigData)
let clientSecret = clientConfigData.clientSecret; tokenExpirationDate = clientConfigData.tokenExpiration;
const data = { if (!tokenExpirationDate || moment().isAfter(tokenExpirationDate)) {
grant_type: 'client_credentials', let clientId, clientSecret
client_id: clientId, if (JSON.parse(env.USE_SECRETS_DB)) {
client_secret: clientSecret, clientId = clientConfigData.clientId;
scope: 'role:app catalog:read supply:read organization:read network:write network:read' clientSecret = clientConfigData.clientSecret;
}; } else {
clientId = env.CLIENT_ID
clientSecret = env.CLIENT_SECRET
};
const body = Object.keys(data) const data = {
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`) grant_type: 'client_credentials',
.join('&'); client_id: clientId,
client_secret: clientSecret,
scope: 'role:app catalog:read supply:read organization:read network:write network:read'
};
const response = await fetch(env.API_ENDPOINT, { const body = Object.keys(data)
method: 'POST', .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
headers: { .join('&');
'Content-Type': 'application/x-www-form-urlencoded',
},
body,
});
const responseData = await response.json(); const response = await fetch(env.API_ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body,
});
if (response.ok) { const responseData = await response.json();
spinner.succeed();
if (response.ok)
spinner.succeed();
else {
spinner.fail();
criticalError(new Error(`Token request failed with status: ${response.status} - ${response.statusText}`));
}
let tokenExpirationDate = moment()
.add(responseData.expires_in, 's')
.format('YYYY-MM-DD HH:mm:ss');
await updateClientConfig(
clientId,
clientSecret,
responseData.access_token,
tokenExpirationDate
);
return tokenExpirationDate;
} else { } else {
spinner.fail(); spinner.text = 'Using stored token...'
criticalError(new Error(`Token request failed with status: ${response.status} - ${response.statusText}`)); spinner.succeed();
return tokenExpirationDate;
} }
let tokenExpirationDate = moment() } catch (err) {
.add(responseData.expires_in, 's') spinner.fail();
.format('YYYY-MM-DD HH:mm:ss'); throw err;
await updateClientConfig(
clientId,
clientSecret,
responseData.access_token,
tokenExpirationDate
);
return tokenExpirationDate;
} else {
spinner.text = 'Using stored token...'
spinner.succeed();
return tokenExpirationDate;
} }
} }
@ -94,29 +109,30 @@ export async function getCurrentTokenExpiration() {
/** /**
* Updates the Access Token in the client config table * Updates the Access Token in the client config table
* *
* @param {sequelize.models} models
* @param {String} clientId * @param {String} clientId
* @param {String} clientSecret * @param {String} clientSecret
* @param {String} accessToken * @param {String} accessToken
* @param {String} tokenExpirationDate * @param {String} tokenExpirationDate
*/ */
export async function updateClientConfig(clientId, clientSecret, accessToken, tokenExpirationDate) { export async function updateClientConfig(clientId, clientSecret, accessToken, tokenExpirationDate) {
try { try {
const spinner = ora(`Updating token...`).start(); const spinner = ora(`Updating token...`).start();
await models.clientConfig.upsert({ if (!JSON.parse(process.env.USE_SECRETS_DB))
id: 1, clientId = clientSecret = null
clientId: clientId,
clientSecret: clientSecret, await models.clientConfig.upsert({
currentToken: accessToken, id: 1,
tokenExpiration: tokenExpirationDate, clientId: clientId,
requestLimit: 500, clientSecret: clientSecret,
}); currentToken: accessToken,
spinner.succeed(); tokenExpiration: tokenExpirationDate
} catch (error) { });
spinner.fail(); spinner.succeed();
console.log('There was a error while updating the client config'); } catch (error) {
console.log(error); spinner.fail();
} console.log('There was a error while updating the client config');
console.log(error);
}
} }
/** /**
@ -325,9 +341,8 @@ export async function syncConn(){
let i = 1; let i = 1;
for (let connection of connections){ for (let connection of connections){
spinner.text = `Syncing ${i++} connections...` spinner.text = `Syncing ${i++} connections...`
if (connection.isConnected == false){ if (connection.isConnected == false)
continue; continue;
}
let remoteConnection = remoteConnections.find(remoteConnection => remoteConnection == connection.organizationId); let remoteConnection = remoteConnections.find(remoteConnection => remoteConnection == connection.organizationId);
if (remoteConnection == undefined){ if (remoteConnection == undefined){
@ -710,6 +725,6 @@ export async function insertItem(tradeItem, supplier) {
* @param {err} * @param {err}
**/ **/
export async function criticalError(err) { export async function criticalError(err) {
console.log(chalk.red.bold(`[ERROR]`), chalk.red(`${err.name}: ${err.message}`)); console.log(chalk.red.bold(`[CRITICAL]`), chalk.red(`${err.message}`));
process.exit(); process.exit();
} }