refs #4823 Improved code
This commit is contained in:
parent
bfe36b1284
commit
1a97f16a11
|
@ -10,6 +10,7 @@ class Floriday {
|
|||
async start() {
|
||||
try {
|
||||
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_SUPPLIER)) await utils.syncSuppliers();
|
||||
if (JSON.parse(env.SYNC_CONN)) await utils.syncConn();
|
||||
|
|
|
@ -12,14 +12,11 @@ const clientConfig = {
|
|||
clientSecret: {
|
||||
type: Sequelize.STRING,
|
||||
},
|
||||
requestLimit: {
|
||||
type: Sequelize.INTEGER,
|
||||
},
|
||||
currentToken: {
|
||||
type: Sequelize.STRING(2000),
|
||||
},
|
||||
tokenExpiration: {
|
||||
type: Sequelize.STRING,
|
||||
type: Sequelize.DATE,
|
||||
},
|
||||
};
|
||||
|
||||
|
|
|
@ -2,9 +2,11 @@ import { Sequelize } from 'sequelize';
|
|||
import dotenv from 'dotenv';
|
||||
import chalk from 'chalk';
|
||||
import ora from 'ora';
|
||||
import { criticalError } from './../utils.js';
|
||||
import { criticalError, updateClientConfig } from './../utils.js';
|
||||
|
||||
dotenv.config();
|
||||
const env = process.env;
|
||||
|
||||
console.clear()
|
||||
console.log(chalk.hex('#06c581')(
|
||||
`
|
||||
|
@ -178,17 +180,6 @@ if (JSON.parse(process.env.FORCE_SYNC)) {
|
|||
const modSpinner = ora(`${action} models...`).start();
|
||||
try {
|
||||
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();
|
||||
}
|
||||
catch (err) {
|
||||
|
|
145
utils.js
145
utils.js
|
@ -13,61 +13,76 @@ const env = process.env;
|
|||
* @returns {Date} tokenExpirationDate formated as YYYY-MM-DD HH:mm:ss
|
||||
*/
|
||||
export async function requestToken() {
|
||||
const clientConfigData = await models.clientConfig.findOne();
|
||||
let spinner;
|
||||
try {
|
||||
spinner = ora(`Requesting new token...`).start();
|
||||
|
||||
if (!clientConfigData)
|
||||
throw new Error('No data found in the client config table')
|
||||
if (!env.CLIENT_ID || !env.CLIENT_SECRET)
|
||||
throw new Error(`You haven't provided the credentials`)
|
||||
|
||||
const spinner = ora(`Requesting new token...`).start();
|
||||
const tokenExpirationDate = clientConfigData.tokenExpiration;
|
||||
const clientConfigData = await models.clientConfig.findOne();
|
||||
|
||||
if (clientConfigData.tokenExpiration == null || moment().isAfter(tokenExpirationDate)) {
|
||||
let clientId = clientConfigData.clientId;
|
||||
let clientSecret = clientConfigData.clientSecret;
|
||||
let tokenExpirationDate;
|
||||
if (clientConfigData)
|
||||
tokenExpirationDate = clientConfigData.tokenExpiration;
|
||||
|
||||
const data = {
|
||||
grant_type: 'client_credentials',
|
||||
client_id: clientId,
|
||||
client_secret: clientSecret,
|
||||
scope: 'role:app catalog:read supply:read organization:read network:write network:read'
|
||||
};
|
||||
if (!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
|
||||
};
|
||||
|
||||
const body = Object.keys(data)
|
||||
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
|
||||
.join('&');
|
||||
const data = {
|
||||
grant_type: 'client_credentials',
|
||||
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, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body,
|
||||
});
|
||||
const body = Object.keys(data)
|
||||
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
|
||||
.join('&');
|
||||
|
||||
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) {
|
||||
spinner.succeed();
|
||||
const responseData = await response.json();
|
||||
|
||||
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 {
|
||||
spinner.fail();
|
||||
criticalError(new Error(`Token request failed with status: ${response.status} - ${response.statusText}`));
|
||||
spinner.text = 'Using stored token...'
|
||||
spinner.succeed();
|
||||
return tokenExpirationDate;
|
||||
}
|
||||
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 {
|
||||
spinner.text = 'Using stored token...'
|
||||
spinner.succeed();
|
||||
return tokenExpirationDate;
|
||||
} catch (err) {
|
||||
spinner.fail();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -94,29 +109,30 @@ export async function getCurrentTokenExpiration() {
|
|||
/**
|
||||
* Updates the Access Token in the client config table
|
||||
*
|
||||
* @param {sequelize.models} models
|
||||
* @param {String} clientId
|
||||
* @param {String} clientSecret
|
||||
* @param {String} accessToken
|
||||
* @param {String} tokenExpirationDate
|
||||
*/
|
||||
export async function updateClientConfig(clientId, clientSecret, accessToken, tokenExpirationDate) {
|
||||
try {
|
||||
const spinner = ora(`Updating token...`).start();
|
||||
await models.clientConfig.upsert({
|
||||
id: 1,
|
||||
clientId: clientId,
|
||||
clientSecret: clientSecret,
|
||||
currentToken: accessToken,
|
||||
tokenExpiration: tokenExpirationDate,
|
||||
requestLimit: 500,
|
||||
});
|
||||
spinner.succeed();
|
||||
} catch (error) {
|
||||
spinner.fail();
|
||||
console.log('There was a error while updating the client config');
|
||||
console.log(error);
|
||||
}
|
||||
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: clientId,
|
||||
clientSecret: clientSecret,
|
||||
currentToken: accessToken,
|
||||
tokenExpiration: tokenExpirationDate
|
||||
});
|
||||
spinner.succeed();
|
||||
} catch (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;
|
||||
for (let connection of connections){
|
||||
spinner.text = `Syncing ${i++} connections...`
|
||||
if (connection.isConnected == false){
|
||||
if (connection.isConnected == false)
|
||||
continue;
|
||||
}
|
||||
let remoteConnection = remoteConnections.find(remoteConnection => remoteConnection == connection.organizationId);
|
||||
|
||||
if (remoteConnection == undefined){
|
||||
|
@ -710,6 +725,6 @@ export async function insertItem(tradeItem, supplier) {
|
|||
* @param {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();
|
||||
}
|
Loading…
Reference in New Issue