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'); let moment = require('moment');
require('dotenv').config();
require('dotenv').config()
// Source: https://apiv2.bitcoinaverage.com/ // Source: https://apiv2.bitcoinaverage.com/
const divisaTraceback = async(timestamp, divisa, amount) => { const divisaTraceback = async(timestamp, divisa, amount) => {
let crypto = ['BTC', 'ETH', 'LTC'] let crypto = ['BTC', 'ETH', 'LTC']
let normal = ['USD', 'GBP', 'CNY', 'EUR']; let normal = ['USD', 'GBP', 'CNY', 'EUR'];
let opt = { method: 'GET', json: true };
let cryptoHeaders = {
'X-Testing': 'testing',
'x-ba-key': process.env.APIKEY
}
try { try {
if((Date.now() - 7776000000) <= (timestamp * 1000)) { if((Date.now() - 7776000000) <= (timestamp * 1000)) {
if(crypto.includes(divisa) || normal.includes(divisa)) { if(crypto.includes(divisa) || normal.includes(divisa)) {
if(amount > 0) { if(amount >= 0) {
opt.headers = cryptoHeaders;
let divisaTraceback = {}; let divisaTraceback = {};
let resolution = await getResolution(timestamp);
if(crypto.includes(divisa)) { if(crypto.includes(divisa)) {
divisaTraceback[crypto.splice(crypto.indexOf(divisa), 1)[0]] = Number(amount); 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(normal, divisa, true, timestamp, amount, resolution));
Object.assign(divisaTraceback, await requestIteration(crypto, 'USD', false, timestamp, divisaTraceback['USD'])); Object.assign(divisaTraceback, await requestIteration(crypto, 'USD', false, timestamp, divisaTraceback['USD'], resolution));
} }
else { else {
divisaTraceback[normal.splice(normal.indexOf(divisa), 1)[0]] = Number(amount); 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(crypto, divisa, false, timestamp, amount, resolution));
Object.assign(divisaTraceback, await requestIteration(normal, 'BTC', true, timestamp, divisaTraceback['BTC'])); Object.assign(divisaTraceback, await requestIteration(normal, 'BTC', true, timestamp, divisaTraceback['BTC'], resolution));
} }
return(divisaTraceback); 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('Currency target invalid');
} else return('Date out of range') } else return('Date out of range')
} catch(e) { } 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 = { let opt = {
method: 'GET', method: 'GET',
json: true, json: true,
headers: { headers: {
'X-Testing': 'testing',
'x-ba-key': process.env.APIKEY 'x-ba-key': process.env.APIKEY
} }
}; };
let res = {}; let res = {};
for (element in set) { for (element in set) {
if(flag) { 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); let { average } = await request(opt);
res[set[element]] = average * amount; res[set[element]] = average * amount;
} }
else { 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); let { average } = await request(opt);
res[set[element]] = amount / average; res[set[element]] = amount / average;
} }
@ -63,4 +56,20 @@ const requestIteration = async(set, divisa, flag, timestamp, amount) => {
return res; 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; module.exports = divisaTraceback;

View File

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