2024-07-30 18:03:17 +03:00
|
|
|
const pool = require('../database/postgresql.js');
|
|
|
|
const axios = require('axios');
|
2024-07-31 12:48:56 +03:00
|
|
|
const config = require('../config/main.js')();
|
2024-08-11 17:23:23 +03:00
|
|
|
const logger = require('../logger/main.js');
|
2024-07-30 18:03:17 +03:00
|
|
|
|
2024-08-04 13:55:37 +03:00
|
|
|
/**
|
|
|
|
* Saves exchange rate of the fiat currency
|
|
|
|
* @returns {Object} -
|
|
|
|
*/
|
2024-07-30 18:03:17 +03:00
|
|
|
async function save_fiat() {
|
|
|
|
if (!config['currency']['collecting']['fiat']) return;
|
|
|
|
|
|
|
|
config['currency']['fiat'].forEach(
|
|
|
|
(value) => config['currency']['fiat'].forEach(async (pair) => {
|
2024-08-11 17:23:23 +03:00
|
|
|
if(value === pair) return;
|
|
|
|
const res = await axios.get(
|
|
|
|
`https://duckduckgo.com/js/spice/currency/1/${value}/${pair}`,
|
|
|
|
{
|
|
|
|
timeout: 3000,
|
2024-07-30 18:03:17 +03:00
|
|
|
});
|
2024-08-11 17:23:23 +03:00
|
|
|
|
|
|
|
const regExp = new RegExp('\\(\\s*(.*)\\s*\\);$', 'mg');
|
|
|
|
const data = JSON.parse(Array.from(res.data.matchAll(regExp))[0][1]);
|
|
|
|
|
|
|
|
delete data['terms'];
|
|
|
|
delete data['privacy'];
|
|
|
|
|
|
|
|
logger.debug(JSON.stringify(data));
|
|
|
|
|
|
|
|
if (res.status !== 200) {
|
|
|
|
logger.error(`DuckDuckGo ended with the status ${res.status}`);
|
|
|
|
return;
|
2024-07-30 18:03:17 +03:00
|
|
|
}
|
2024-08-11 17:23:23 +03:00
|
|
|
|
|
|
|
const point = data['to'][0]['mid'].toString().indexOf('.') + 4;
|
|
|
|
|
|
|
|
pool.query('SELECT * FROM currency WHERE from_currency = $1 AND conv_currency = $2 AND date = $3',
|
|
|
|
[ value, pair, new Date(data['timestamp']).toLocaleDateString() ]
|
|
|
|
).then(async (db) => {
|
|
|
|
if (db['rows'][0]) return;
|
|
|
|
|
|
|
|
await pool.query(`INSERT INTO currency (from_currency, conv_currency, rate, date) VALUES ($1, $2, $3, $4)`,
|
|
|
|
[
|
|
|
|
value,
|
|
|
|
pair,
|
|
|
|
data['to'][0]['mid'].toString().slice(0, point),
|
|
|
|
new Date(data['timestamp']).toLocaleDateString()
|
|
|
|
]);
|
|
|
|
});
|
2024-07-30 18:03:17 +03:00
|
|
|
})
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2024-08-01 00:43:18 +03:00
|
|
|
module.exports = save_fiat;
|