Kekkai/collect-currency/save_crypto.js

90 lines
3.1 KiB
JavaScript
Raw Normal View History

2024-08-14 17:14:59 +03:00
const config = require('../shared/config/src/main.js')();
const axios = require('axios');
2024-08-14 17:14:59 +03:00
const pool = require('../shared/database/src/postgresql.js');
const logger = require('../shared/logger/src/main.js');
const coinapiKeys = config['currency']['coinapiKeys'];
let apiKeyIndex = 0;
let depth = coinapiKeys.length;
function save_crypto() {
if (!config['currency']['collecting']['crypto']) return;
if (coinapiKeys[apiKeyIndex] === undefined) return;
if (depth <= 0) {
logger.info('Rate limit on all coinapi API keys');
new Error('Rate limit on all coinapi API keys');
return;
}
2024-08-17 16:40:20 +03:00
logger.info(
`Active coinapi key: ${coinapiKeys[apiKeyIndex]} (${coinapiKeys.length - 1} / ${apiKeyIndex})`,
);
2024-08-17 16:40:20 +03:00
config['currency']['crypto'].forEach((value) =>
config['currency']['crypto'].forEach((pair) => {
if (value === pair) return;
2024-08-17 16:40:20 +03:00
axios
.get(
`https://rest.coinapi.io/v1/exchangerate/${value}/${pair}`,
{
timeout: 3000,
headers: {
'X-CoinAPI-Key': coinapiKeys[apiKeyIndex],
},
},
)
.then(async (res) => {
const data = res.data;
const point = data['rate'].toString().indexOf('.') + 4;
logger.debug(JSON.stringify(data));
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,
2024-08-17 16:40:20 +03:00
new Date(data['time']).toLocaleDateString(),
],
);
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-17 16:40:20 +03:00
[
value,
pair,
data['rate'].toString().slice(0, point),
new Date(data['time']).toLocaleDateString(),
],
);
})
.catch((err) => {
if (err.response?.data.detail)
logger.error(err.response.data.detail);
if (err.response?.data.status === 429) {
logger.info('CoinAPI rate limited, rotating token');
rotate_key(coinapiKeys);
depth--;
save_crypto();
}
});
}),
);
}
/**
* Changing API keys
* @param {Array} list - List of all keys
* @returns {number} - Outputs the number of the key that should work
*/
function rotate_key(list) {
2024-08-14 21:20:08 +03:00
apiKeyIndex = list.indexOf(coinapiKeys[apiKeyIndex]) + 1;
}
2024-08-17 16:40:20 +03:00
module.exports = save_crypto;