2024-08-14 17:14:59 +03:00
|
|
|
const pool = require('../shared/database/src/postgresql.js');
|
2024-07-30 18:03:17 +03:00
|
|
|
const axios = require('axios');
|
2024-08-14 17:14:59 +03:00
|
|
|
const config = require('../shared/config/src/main.js')();
|
|
|
|
const logger = require('../shared/logger/src/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;
|
|
|
|
|
2024-08-17 16:40:20 +03:00
|
|
|
config['currency']['fiat'].forEach((value) =>
|
|
|
|
config['currency']['fiat'].forEach(async (pair) => {
|
|
|
|
if (value === pair) return;
|
|
|
|
await axios
|
|
|
|
.get(
|
|
|
|
`https://duckduckgo.com/js/spice/currency/1/${value}/${pair}`,
|
|
|
|
{
|
|
|
|
timeout: 3000,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
.then(async (res) => {
|
2024-08-12 18:21:34 +03:00
|
|
|
const regExp = new RegExp('\\(\\s*(.*)\\s*\\);$', 'mg');
|
2024-08-17 16:40:20 +03:00
|
|
|
const data = JSON.parse(
|
|
|
|
Array.from(res.data.matchAll(regExp))[0][1],
|
|
|
|
);
|
2024-08-12 18:21:34 +03:00
|
|
|
|
|
|
|
delete data['terms'];
|
|
|
|
delete data['privacy'];
|
|
|
|
|
|
|
|
logger.debug(JSON.stringify(data));
|
|
|
|
|
2024-08-17 16:40:20 +03:00
|
|
|
const point =
|
|
|
|
data['to'][0]['mid'].toString().indexOf('.') + 4;
|
2024-08-12 18:21:34 +03:00
|
|
|
|
2024-08-17 16:40:20 +03:00
|
|
|
const db = await pool.query(
|
|
|
|
'SELECT * FROM currency WHERE ' +
|
|
|
|
'from_currency = $1 AND conv_currency = $2 AND date = $3',
|
|
|
|
[
|
|
|
|
value,
|
|
|
|
pair,
|
|
|
|
new Date(data['timestamp']).toLocaleDateString(),
|
|
|
|
],
|
|
|
|
);
|
2024-08-12 18:21:34 +03:00
|
|
|
|
|
|
|
if (db['rows'][0]) return;
|
2024-08-17 16:40:20 +03:00
|
|
|
await pool.query(
|
|
|
|
`INSERT INTO currency (from_currency, conv_currency, rate, date) VALUES ($1, $2, $3, $4)`,
|
2024-08-12 18:21:34 +03:00
|
|
|
[
|
|
|
|
value,
|
|
|
|
pair,
|
|
|
|
data['to'][0]['mid'].toString().slice(0, point),
|
2024-08-17 16:40:20 +03:00
|
|
|
new Date(data['timestamp']).toLocaleDateString(),
|
|
|
|
],
|
|
|
|
);
|
|
|
|
})
|
|
|
|
.catch((err) => {
|
|
|
|
logger.error(err);
|
|
|
|
setTimeout(save_fiat, err.config.timeout);
|
|
|
|
});
|
|
|
|
}),
|
2024-07-30 18:03:17 +03:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2024-08-17 16:40:20 +03:00
|
|
|
module.exports = save_fiat;
|