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,42 +111,47 @@ const main = async () => {
}]); }]);
if (insertMenu == 'Insert current register') { if (insertMenu == 'Insert current register') {
if (await validateInsertion(carbonCredit)) { if (await validateInsertion(carbonCredit)) {
carbonCredit.conversionPrice = await divisaTraceback( try{
moment.utc(carbonCredit.cancelDate + ' +0000', 'DD-MM-YYYY HH:mm Z').unix(), carbonCredit.conversionPrice = await divisaTraceback(
carbonCredit.cancelPrice.divisa, moment.utc(carbonCredit.cancelDate + ' +0000', 'DD-MM-YYYY HH:mm Z').unix(),
carbonCredit.cancelPrice.qty carbonCredit.cancelPrice.divisa,
); carbonCredit.cancelPrice.qty
showData(carbonCredit, 0); );
serialNoPart=carbonCredit.SerialNo.split('-'); if(carbonCredit.conversionPrice === 'error') throw new Error('Error at getting currencies price.');
serialFloor=serialNoPart[7]; showData(carbonCredit, 0);
serialTop=serialNoPart[8]; serialNoPart=carbonCredit.SerialNo.split('-');
var totalCC = 1+parseInt(serialTop)-parseInt(serialFloor); serialFloor=serialNoPart[7];
let { input } = await inquirer.prompt([{ serialTop=serialNoPart[8];
type: 'input', var totalCC = 1+parseInt(serialTop)-parseInt(serialFloor);
name: 'input', let { input } = await inquirer.prompt([{
message: 'Data is correct, you will insert '+ String(totalCC) +" carbon credits y | n:", type: 'input',
}]); name: 'input',
if (input == 'y') { message: 'Data is correct, you will insert '+ String(totalCC) +" carbon credits y | n:",
carbonCredit.issueDate = moment(carbonCredit.issueDate + ' +0000', 'DD-MM-YYYY HH:mm Z').unix(); }]);
carbonCredit.cancelDate = moment(carbonCredit.cancelDate + ' +0000', 'DD-MM-YYYY HH:mm Z').unix(); if (input == 'y') {
carbonCredit.ccVintageStart = moment(carbonCredit.ccVintageStart + ' +0000', 'DD-MM-YYYY HH:mm Z').unix(); carbonCredit.issueDate = moment(carbonCredit.issueDate + ' +0000', 'DD-MM-YYYY HH:mm Z').unix();
carbonCredit.ccVintageEnd = moment(carbonCredit.ccVintageEnd + ' +0000', 'DD-MM-YYYY HH:mm Z').unix(); carbonCredit.cancelDate = moment(carbonCredit.cancelDate + ' +0000', 'DD-MM-YYYY HH:mm Z').unix();
carbonCredit.CCID = await hashSortCoerce.hash(carbonCredit); carbonCredit.ccVintageStart = moment(carbonCredit.ccVintageStart + ' +0000', 'DD-MM-YYYY HH:mm Z').unix();
const hash = await db.put(carbonCredit); carbonCredit.ccVintageEnd = moment(carbonCredit.ccVintageEnd + ' +0000', 'DD-MM-YYYY HH:mm Z').unix();
console.log(`Successful insertion, CCID: ${carbonCredit.CCID}, hash: ${hash}.`); carbonCredit.CCID = await hashSortCoerce.hash(carbonCredit);
for(var i=parseInt(serialFloor)+1; i<=serialTop; i++){ const hash = await db.put(carbonCredit);
var tempCarbonCredit = {...carbonCredit}; console.log(`Successful insertion, CCID: ${carbonCredit.CCID}, hash: ${hash}.`);
tempCarbonCredit.SerialNo= await asyncCCSerialNo(serialNoPart,i) for(var i=parseInt(serialFloor)+1; i<=serialTop; i++){
tempCarbonCredit.CCID = await hashSortCoerce.hash(tempCarbonCredit); var tempCarbonCredit = {...carbonCredit};
const hash = await db.put(tempCarbonCredit); tempCarbonCredit.SerialNo= await asyncCCSerialNo(serialNoPart,i)
console.log(`Successful insertion, CCID: ${tempCarbonCredit.CCID}, hash: ${hash}.`); tempCarbonCredit.CCID = await hashSortCoerce.hash(tempCarbonCredit);
} const hash = await db.put(tempCarbonCredit);
console.log(`Inserted ${totalCC} carbon credits.`); console.log(`Successful insertion, CCID: ${tempCarbonCredit.CCID}, hash: ${hash}.`);
break; }
} else { console.log(`Inserted ${totalCC} carbon credits.`);
console.clear(); break;
console.log('Insertion aborted'); } else {
break; console.clear();
console.log('Insertion aborted');
break;
}
} catch(e) {
console.log(e.message);
} }
} }
else { else {
@ -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) {
carbonCredit[insertMenu] = date.format('DD-MM-YYYY HH:mm Z'); 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') ||
else if (date.isValid() && insertMenu != 'cancelDate' && moment() >= date) { (date >= moment().subtract(1, 'year') && process.env.API_MODE == 'startup') ||
carbonCredit[insertMenu] = date.format('DD-MM-YYYY HH:mm Z'); (date >= moment().subtract(7, 'year') && process.env.API_MODE == 'grow')) {
} else console.log(' Date must follow next syntax: dd-mm-yyyy hh-mm and cancel date must be 10 days old at most'); carbonCredit[insertMenu] = date.format('DD-MM-YYYY HH:mm Z');
} 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') { else if (insertMenu == 'qty') {
if (parseFloat(input)) carbonCredit.cancelPrice[insertMenu] = input; if (parseFloat(input)) carbonCredit.cancelPrice[insertMenu] = input;