-
Notifications
You must be signed in to change notification settings - Fork 0
/
currency_api.js
71 lines (64 loc) · 1.97 KB
/
currency_api.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const dbDebugger = require('debug')('app:dbDebugger');
const Currencies = require('./models/currencies');
const fetch = require('node-fetch');
require('dotenv').config()
var myHeaders = new fetch.Headers();
myHeaders.append("apikey", process.env.CURRENCY_CONVERTOR_API_KEY);
var requestOptions = {
method: 'GET',
redirect: 'follow',
headers: myHeaders
};
//runs once
async function getFromApiAndCreateDB() {
var base = 'EGP';
const response = await fetch(`https://api.apilayer.com/exchangerates_data/latest?&base=${base}`, requestOptions)
const result = await response.text();
jsonrResult = JSON.parse(result);
var currencies = new Currencies({
base: 'EGP',
rates: jsonrResult.rates
});
await currencies.save();
dbDebugger(currencies);
}
async function getFromApiAndUpdateDB() {
try {
var base = 'EGP';
const response = await fetch(`https://api.apilayer.com/exchangerates_data/latest?&base=${base}`, requestOptions)
const result = await response.text();
jsonrResult = JSON.parse(result);
let currencies = await Currencies.findOneAndUpdate({ base: 'EGP' }, {
$set: {
base: base,
rates: jsonrResult.rates
}
});
dbDebugger('currencies', currencies);
} catch (error) {
dbDebugger('error', error);
}
}
// convertor(from x to y) = amount * rate ... rate = rate(y)/rate(x)
async function convertor(from, to, amount) {
try {
let rate;
let calcAmount;
await Currencies.find().then(
result => {
if (from.toUpperCase === 'EGP') {
rate = result[0].rates.get(to.toUpperCase());
calcAmount = rate * parseFloat(amount);
}
rate = (result[0].rates.get(to.toUpperCase())) / (result[0].rates.get(from.toUpperCase()));
calcAmount = rate * parseFloat(amount);
dbDebugger(calcAmount);
}
)
return calcAmount;
} catch (error) {
dbDebugger('error', error);
}
}
exports.convertor = convertor;
exports.updateDB = getFromApiAndUpdateDB;