diff --git a/utils.js b/utils.js index a54c625..16d224d 100644 --- a/utils.js +++ b/utils.js @@ -17,53 +17,36 @@ export async function requestToken(isForce = false) { try { const clientConfigData = await models.clientConfig.findOne(); - let tokenExpirationDate, token; + let tokenExpiration, token; if (clientConfigData) { token = clientConfigData.currentToken; - tokenExpirationDate = clientConfigData.tokenExpiration; + tokenExpiration = clientConfigData.tokenExpiration; } - if (isForce || !token || !tokenExpirationDate || moment().isAfter(tokenExpirationDate)) { - let clientId, clientSecret - if (JSON.parse(env.USE_SECRETS_DB)) { - clientId = clientConfigData.clientId; - clientSecret = clientConfigData.clientSecret; - } else { - clientId = env.CLIENT_ID - clientSecret = env.CLIENT_SECRET - }; + if (isForce || !token || !tokenExpiration || moment().isAfter(tokenExpiration)) { + 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; - let data = { + const data = new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret, scope: 'role:app catalog:read supply:read organization:read network:write network:read' - }; - - data = Object.keys(data) - .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`) - .join('&') - + }).toString(); const headers = { 'Content-Type': 'application/x-www-form-urlencoded' }; - const response = (await vnRequest('POST', env.API_ENDPOINT, data, headers)).data; - if (response.statusText = 'OK') - spinner.succeed(); - else { - spinner.fail(); - criticalError(new Error(`Token request failed with status: ${response.status} - ${response.statusText}`)); - } - let tokenExpirationDate = moment() + const tokenExpiration = moment() .add(response.expires_in, 's') .format('YYYY-MM-DD HH:mm:ss'); - - await updateClientConfig( + + await updateClientConfig({ clientId, clientSecret, - response.access_token, - tokenExpirationDate - ); + currentToken: response.access_token, + tokenExpiration, + }); + spinner.succeed(); } else spinner.succeed('Using stored token...'); } catch (err) { @@ -116,29 +99,18 @@ export async function getCurrentTokenExpiration() { /** * Updates the access token in the client config table * - * @param {String} clientId - * @param {String} clientSecret - * @param {String} accessToken - * @param {String} tokenExpirationDate + * @param {Array} clientConfig [clientId, clientSecret, currenToken, tokenExpiration] */ -export async function updateClientConfig(clientId, clientSecret, currentToken, tokenExpiration) { - try { - const spinner = ora(`Updating token...`).start(); - if (!JSON.parse(process.env.USE_SECRETS_DB)) - clientId = clientSecret = null - - await models.clientConfig.upsert({ - id: 1, - clientId, - clientSecret, - currentToken, - tokenExpiration, - }); - spinner.succeed(); - } catch (err) { - spinner.fail(); - throw(err); - } +export async function updateClientConfig(clientConfig) { + try { + if (!JSON.parse(process.env.USE_SECRETS_DB)) clientId = clientSecret = null + await models.clientConfig.upsert({ + id: 1, + ...clientConfig, + }); + } catch (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 */ @@ -380,7 +320,7 @@ export async function syncSupplyLines() { /** * Insert trade item and dependences in db * - * @param {array} tradeItem + * @param {Array} tradeItem */ export async function insertItem(tradeItem) { let tx; @@ -474,7 +414,7 @@ export async function insertItem(tradeItem) { /** * Insert warehouse in db * - * @param {array} warehouse + * @param {Array} warehouse */ export async function insertWarehouse(warehouse) { let tx; @@ -500,7 +440,7 @@ export async function insertWarehouse(warehouse) { /** * Insert organization in db * - * @param {array} organization + * @param {Array} organization */ export async function insertOrganization(organization) { let tx; @@ -569,8 +509,7 @@ export async function deleteConnections() { isExists = false; } - if (ghostConnections.length) - spinner = ora(`Deleting connections that aren't in the db...`).start(); + if (ghostConnections.length) spinner = ora(`Deleting connections that aren't in the db...`).start(); for (let connection of ghostConnections) { await vnRequest('DELETE', `${env.API_URL}/connections/${connection}`); @@ -586,12 +525,12 @@ export async function deleteConnections() { /** * Perform a REST request * - * @param {string} url - * @param {string} method - * @param {array} body - * @param {array} header + * @param {String} url + * @param {String} method + * @param {Array} body + * @param {Array} header * - * @return {array} + * @return {Array} **/ export async function vnRequest(method, url, data, 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++) { try { - if (['GET', 'DELETE'].includes(method)) - return await axios({method, url, headers}); - else - return await axios({method, url, data, headers}); + return (['GET', 'DELETE'].includes(method)) + ? await axios({method, url, headers}) + : axios({method, url, data, headers}); } catch (err) { switch (err.code) { case 'ECONNRESET': // Client network socket TLS @@ -630,16 +568,14 @@ export async function vnRequest(method, url, data, headers) { case 401: // Unauthorized warning(err); await requestToken(true); - headers.Authorization ? - headers.Authorization = `Bearer ${await getCurrentToken()}` : - criticalError(err); + headers.Authorization + ? headers.Authorization = `Bearer ${await getCurrentToken()}` + : criticalError(err); break; - default: - criticalError(err); + default: criticalError(err); } break; - default: - criticalError(err); + default: criticalError(err); } } } @@ -651,7 +587,7 @@ export async function vnRequest(method, url, data, headers) { * @param {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(); } @@ -661,5 +597,5 @@ export async function criticalError(err) { * @param {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)); } \ No newline at end of file