Fixing api crash

This commit is contained in:
Oscar Martinez 2020-06-03 21:53:48 -05:00
parent 8ab6dd9370
commit a6867dd387
3 changed files with 79 additions and 63 deletions

0
.envSample Normal file
View File

View File

@ -1,61 +1,54 @@
const request = require('request-promise');
require('dotenv').config()
let moment = require('moment');
require('dotenv').config();
// Source: https://apiv2.bitcoinaverage.com/
const divisaTraceback = async(timestamp, divisa, amount) => {
let crypto = ['BTC', 'ETH', 'LTC']
let normal = ['USD', 'GBP', 'CNY', 'EUR'];
let opt = { method: 'GET', json: true };
let cryptoHeaders = {
'X-Testing': 'testing',
'x-ba-key': process.env.APIKEY
}
try {
if((Date.now() - 7776000000) <= (timestamp * 1000)) {
if(crypto.includes(divisa) || normal.includes(divisa)) {
if(amount > 0) {
opt.headers = cryptoHeaders;
if(amount >= 0) {
let divisaTraceback = {};
let resolution = await getResolution(timestamp);
if(crypto.includes(divisa)) {
divisaTraceback[crypto.splice(crypto.indexOf(divisa), 1)[0]] = Number(amount);
Object.assign(divisaTraceback, await requestIteration(normal, divisa, true, timestamp, amount));
Object.assign(divisaTraceback, await requestIteration(crypto, 'USD', false, timestamp, divisaTraceback['USD']));
Object.assign(divisaTraceback, await requestIteration(normal, divisa, true, timestamp, amount, resolution));
Object.assign(divisaTraceback, await requestIteration(crypto, 'USD', false, timestamp, divisaTraceback['USD'], resolution));
}
else {
divisaTraceback[normal.splice(normal.indexOf(divisa), 1)[0]] = Number(amount);
Object.assign(divisaTraceback, await requestIteration(crypto, divisa, false, timestamp, amount));
Object.assign(divisaTraceback, await requestIteration(normal, 'BTC', true, timestamp, divisaTraceback['BTC']));
Object.assign(divisaTraceback, await requestIteration(crypto, divisa, false, timestamp, amount, resolution));
Object.assign(divisaTraceback, await requestIteration(normal, 'BTC', true, timestamp, divisaTraceback['BTC'], resolution));
}
return(divisaTraceback);
} else return('The amount must be greater that 0');
} else return('The amount must be 1 or higher');
} else return('Currency target invalid');
} else return('Date out of range')
} catch(e) {
return(e);
throw 'error';
}
};
const requestIteration = async(set, divisa, flag, timestamp, amount) => {
const requestIteration = async(set, divisa, flag, timestamp, amount, resolution) => {
let opt = {
method: 'GET',
json: true,
headers: {
'X-Testing': 'testing',
'x-ba-key': process.env.APIKEY
}
};
let res = {};
for (element in set) {
if(flag) {
opt.uri = `https://apiv2.bitcoinaverage.com/indices/global/history/${divisa}${set[element]}?at=${timestamp}&resolution=hour`;
opt.uri = `https://apiv2.bitcoinaverage.com/indices/global/history/${divisa}${set[element]}?at=${timestamp}&resolution=${resolution}`;
let { average } = await request(opt);
res[set[element]] = average * amount;
}
else {
opt.uri = `https://apiv2.bitcoinaverage.com/indices/global/history/${set[element]}${divisa}?at=${timestamp}&resolution=hour`;
opt.uri = `https://apiv2.bitcoinaverage.com/indices/global/history/${set[element]}${divisa}?at=${timestamp}&resolution=${resolution}`;
let { average } = await request(opt);
res[set[element]] = amount / average;
}
@ -63,4 +56,20 @@ const requestIteration = async(set, divisa, flag, timestamp, amount) => {
return res;
};
const getResolution = async(timestamp) => {
let resolution = 'day';
let momentTime = moment(timestamp);
if(process.env.API_MODE == 'dev') {
if(momentTime >= moment().subtract(2, 'hours')) resolution = 'minute';
else if(momentTime >= moment().subtract(10, 'days')) resolution = 'hour';
} else if(process.env.API_MODE == 'startup' || process.env.API_MODE == 'grow') {
if(momentTime >= moment().subtract(24, 'hours')) resolution = 'minute';
else if(momentTime >= moment().subtract(31, 'days')) resolution = 'hour';
} else throw new Error('Bad config');
return resolution;
}
module.exports = divisaTraceback;

View File

@ -91,7 +91,7 @@ const main = async () => {
}
while (true) {
await init();
console.clear();
//console.clear();
console.log('Select one to modify the field.\n');
let carbonCreditMenu = await generateData(carbonCredit, 0);
let { insertMenu } = await inquirer.prompt([{
@ -111,11 +111,13 @@ const main = async () => {
}]);
if (insertMenu == 'Insert current register') {
if (await validateInsertion(carbonCredit)) {
try{
carbonCredit.conversionPrice = await divisaTraceback(
moment.utc(carbonCredit.cancelDate + ' +0000', 'DD-MM-YYYY HH:mm Z').unix(),
carbonCredit.cancelPrice.divisa,
carbonCredit.cancelPrice.qty
);
if(carbonCredit.conversionPrice === 'error') throw new Error('Error at getting currencies price.');
showData(carbonCredit, 0);
serialNoPart=carbonCredit.SerialNo.split('-');
serialFloor=serialNoPart[7];
@ -148,6 +150,9 @@ const main = async () => {
console.log('Insertion aborted');
break;
}
} catch(e) {
console.log(e.message);
}
}
else {
await showErrorData(carbonCredit);
@ -182,12 +187,14 @@ const main = async () => {
if (input == '') console.log('Input mustn\'t be empty');
else if (insertMenu == 'issueDate' || insertMenu == 'cancelDate' || insertMenu == 'ccVintageStart' || insertMenu == 'ccVintageEnd') {
const date = moment.utc(input + ' +0000', 'DD-MM-YYYY HH:mm');
if (date.isValid() && insertMenu == 'cancelDate' && moment() >= date && date >= moment().subtract(10, 'days')) {
if(date.isValid() && moment() >= date) {
if(insertMenu != 'cancelDate') carbonCredit[insertMenu] = date.format('DD-MM-YYYY HH:mm Z');
else if((date >= moment().subtract(3, 'months') && process.env.API_MODE == 'dev') ||
(date >= moment().subtract(1, 'year') && process.env.API_MODE == 'startup') ||
(date >= moment().subtract(7, 'year') && process.env.API_MODE == 'grow')) {
carbonCredit[insertMenu] = date.format('DD-MM-YYYY HH:mm Z');
}
else if (date.isValid() && insertMenu != 'cancelDate' && moment() >= date) {
carbonCredit[insertMenu] = date.format('DD-MM-YYYY HH:mm Z');
} else console.log(' Date must follow next syntax: dd-mm-yyyy hh-mm and cancel date must be 10 days old at most');
} else console.error(' Date is too old to get pricing data');
} else console.error(' Date must follow next syntax: dd-mm-yyyy hh-mm and can\'t be in the future');
}
else if (insertMenu == 'qty') {
if (parseFloat(input)) carbonCredit.cancelPrice[insertMenu] = input;