refs #4823 Refactor

This commit is contained in:
Guillermo Bonet 2023-05-19 08:47:32 +02:00
parent efa11df1a4
commit b1de54db1e
1 changed files with 44 additions and 108 deletions

136
utils.js
View File

@ -17,53 +17,36 @@ export async function requestToken(isForce = false) {
try { try {
const clientConfigData = await models.clientConfig.findOne(); const clientConfigData = await models.clientConfig.findOne();
let tokenExpirationDate, token; let tokenExpiration, token;
if (clientConfigData) { if (clientConfigData) {
token = clientConfigData.currentToken; token = clientConfigData.currentToken;
tokenExpirationDate = clientConfigData.tokenExpiration; tokenExpiration = clientConfigData.tokenExpiration;
} }
if (isForce || !token || !tokenExpirationDate || moment().isAfter(tokenExpirationDate)) { if (isForce || !token || !tokenExpiration || moment().isAfter(tokenExpiration)) {
let clientId, clientSecret const clientId = JSON.parse(env.USE_SECRETS_DB) ? clientConfigData.clientId || env.CLIENT_ID : env.CLIENT_ID;
if (JSON.parse(env.USE_SECRETS_DB)) { const clientSecret = JSON.parse(env.USE_SECRETS_DB) ? clientConfigData.clientSecret || env.CLIENT_SECRET : env.CLIENT_SECRET;
clientId = clientConfigData.clientId;
clientSecret = clientConfigData.clientSecret;
} else {
clientId = env.CLIENT_ID
clientSecret = env.CLIENT_SECRET
};
let data = { const data = new URLSearchParams({
grant_type: 'client_credentials', grant_type: 'client_credentials',
client_id: clientId, client_id: clientId,
client_secret: clientSecret, client_secret: clientSecret,
scope: 'role:app catalog:read supply:read organization:read network:write network:read' scope: 'role:app catalog:read supply:read organization:read network:write network:read'
}; }).toString();
data = Object.keys(data)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
.join('&')
const headers = { 'Content-Type': 'application/x-www-form-urlencoded' }; const headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
const response = (await vnRequest('POST', env.API_ENDPOINT, data, headers)).data; const response = (await vnRequest('POST', env.API_ENDPOINT, data, headers)).data;
if (response.statusText = 'OK') const tokenExpiration = moment()
spinner.succeed();
else {
spinner.fail();
criticalError(new Error(`Token request failed with status: ${response.status} - ${response.statusText}`));
}
let tokenExpirationDate = moment()
.add(response.expires_in, 's') .add(response.expires_in, 's')
.format('YYYY-MM-DD HH:mm:ss'); .format('YYYY-MM-DD HH:mm:ss');
await updateClientConfig( await updateClientConfig({
clientId, clientId,
clientSecret, clientSecret,
response.access_token, currentToken: response.access_token,
tokenExpirationDate tokenExpiration,
); });
spinner.succeed();
} else } else
spinner.succeed('Using stored token...'); spinner.succeed('Using stored token...');
} catch (err) { } catch (err) {
@ -116,27 +99,16 @@ export async function getCurrentTokenExpiration() {
/** /**
* Updates the access token in the client config table * Updates the access token in the client config table
* *
* @param {String} clientId * @param {Array} clientConfig [clientId, clientSecret, currenToken, tokenExpiration]
* @param {String} clientSecret
* @param {String} accessToken
* @param {String} tokenExpirationDate
*/ */
export async function updateClientConfig(clientId, clientSecret, currentToken, tokenExpiration) { export async function updateClientConfig(clientConfig) {
try { try {
const spinner = ora(`Updating token...`).start(); if (!JSON.parse(process.env.USE_SECRETS_DB)) clientId = clientSecret = null
if (!JSON.parse(process.env.USE_SECRETS_DB))
clientId = clientSecret = null
await models.clientConfig.upsert({ await models.clientConfig.upsert({
id: 1, id: 1,
clientId, ...clientConfig,
clientSecret,
currentToken,
tokenExpiration,
}); });
spinner.succeed();
} catch (err) { } catch (err) {
spinner.fail();
throw(err); throw(err);
} }
} }
@ -153,38 +125,6 @@ export async function sleep(ms) {
}); });
} }
/**
* Recieves an array of functions and executes them in a queue with the given concurrency
*
* @param {Array} fnArray
* @param {Number} concurrency
* @returns
*/
export async function asyncQueue(fnArray, concurrency = 1) {
const results = []; // 1
const queue = fnArray.map((fn, index) => () => fn().then((result) => results[index] = result));
const run = async () => { // 2
const fn = queue.shift();
if (fn) {
await fn();
await run();
}
};
const promises = []; // 3
while (concurrency--) { // 4
promises.push(run());
}
await Promise.all(promises); // 5
return results;
}
/** /**
* Sync the suppliers * Sync the suppliers
*/ */
@ -380,7 +320,7 @@ export async function syncSupplyLines() {
/** /**
* Insert trade item and dependences in db * Insert trade item and dependences in db
* *
* @param {array} tradeItem * @param {Array} tradeItem
*/ */
export async function insertItem(tradeItem) { export async function insertItem(tradeItem) {
let tx; let tx;
@ -474,7 +414,7 @@ export async function insertItem(tradeItem) {
/** /**
* Insert warehouse in db * Insert warehouse in db
* *
* @param {array} warehouse * @param {Array} warehouse
*/ */
export async function insertWarehouse(warehouse) { export async function insertWarehouse(warehouse) {
let tx; let tx;
@ -500,7 +440,7 @@ export async function insertWarehouse(warehouse) {
/** /**
* Insert organization in db * Insert organization in db
* *
* @param {array} organization * @param {Array} organization
*/ */
export async function insertOrganization(organization) { export async function insertOrganization(organization) {
let tx; let tx;
@ -569,8 +509,7 @@ export async function deleteConnections() {
isExists = false; isExists = false;
} }
if (ghostConnections.length) if (ghostConnections.length) spinner = ora(`Deleting connections that aren't in the db...`).start();
spinner = ora(`Deleting connections that aren't in the db...`).start();
for (let connection of ghostConnections) { for (let connection of ghostConnections) {
await vnRequest('DELETE', `${env.API_URL}/connections/${connection}`); await vnRequest('DELETE', `${env.API_URL}/connections/${connection}`);
@ -586,12 +525,12 @@ export async function deleteConnections() {
/** /**
* Perform a REST request * Perform a REST request
* *
* @param {string} url * @param {String} url
* @param {string} method * @param {String} method
* @param {array} body * @param {Array} body
* @param {array} header * @param {Array} header
* *
* @return {array} * @return {Array}
**/ **/
export async function vnRequest(method, url, data, headers) { export async function vnRequest(method, url, data, headers) {
if (!headers) if (!headers)
@ -603,10 +542,9 @@ export async function vnRequest(method, url, data, headers) {
for(let i = 0; i < env.MAX_REQUEST_ATTEMPTS; i++) { for(let i = 0; i < env.MAX_REQUEST_ATTEMPTS; i++) {
try { try {
if (['GET', 'DELETE'].includes(method)) return (['GET', 'DELETE'].includes(method))
return await axios({method, url, headers}); ? await axios({method, url, headers})
else : axios({method, url, data, headers});
return await axios({method, url, data, headers});
} catch (err) { } catch (err) {
switch (err.code) { switch (err.code) {
case 'ECONNRESET': // Client network socket TLS case 'ECONNRESET': // Client network socket TLS
@ -630,16 +568,14 @@ export async function vnRequest(method, url, data, headers) {
case 401: // Unauthorized case 401: // Unauthorized
warning(err); warning(err);
await requestToken(true); await requestToken(true);
headers.Authorization ? headers.Authorization
headers.Authorization = `Bearer ${await getCurrentToken()}` : ? headers.Authorization = `Bearer ${await getCurrentToken()}`
criticalError(err); : criticalError(err);
break; break;
default: default: criticalError(err);
criticalError(err);
} }
break; break;
default: default: criticalError(err);
criticalError(err);
} }
} }
} }
@ -651,7 +587,7 @@ export async function vnRequest(method, url, data, headers) {
* @param {err} * @param {err}
**/ **/
export async function criticalError(err) { export async function criticalError(err) {
console.log(chalk.red.bold(`[CRITICAL]`), chalk.red(`${err.message}`)); console.log(chalk.red.bold(`[CRITICAL]`), chalk.red(err.message));
process.exit(); process.exit();
} }
@ -661,5 +597,5 @@ export async function criticalError(err) {
* @param {err} * @param {err}
**/ **/
export async function warning(err) { export async function warning(err) {
console.log(chalk.yellow.bold(`[WARNING]`), chalk.yellow(`${err.message}`)); console.log(chalk.yellow.bold(`[WARNING]`), chalk.yellow(err.message));
} }