From 3b62109402c20b7312a7d3367d4d180ce410b5cb Mon Sep 17 00:00:00 2001 From: Redume Date: Thu, 1 Aug 2024 00:42:17 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A1=D0=B4=D0=B5=D0=BB=D0=B0=D0=BB=20=D1=81?= =?UTF-8?q?=D0=B1=D0=BE=D1=80=20=D0=BA=D1=80=D0=B8=D0=BF=D1=82=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=D0=BB=D1=8E=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- collect-currency/save_crypto.js | 54 +++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 collect-currency/save_crypto.js diff --git a/collect-currency/save_crypto.js b/collect-currency/save_crypto.js new file mode 100644 index 0000000..ff3fa76 --- /dev/null +++ b/collect-currency/save_crypto.js @@ -0,0 +1,54 @@ +const config = require('../config/main.js')(); +const axios = require('axios'); +const pool = require('../database/postgresql.js'); + +function save_fiat() { + if (!config['currency']['collecting']['crypto']) return; + const depth = config['currency']['cryptoKeys'] + + if (depth <= 0) new Error('Rate limit on all API tokens'); + + config['currency']['crypto'].forEach( + (value) => config['currency']['crypto'].forEach(async (pair) => { + if (value !== pair) { + const cryptoKeyActive = [0]; + const res = await axios.get(`https://rest.coinapi.io/v1/exchangerate/${value}/${pair}`, { + timeout: 3000, + headers: { + 'X-CoinAPI-Key': config['currency']['cryptoKeys'][cryptoKeyActive[0]], + } + }); + + if (res.status === 429) rotate_key(config['currency']['cryptoKeys'], cryptoKeyActive); + + const data = res.data; + const point = data['rate'].toString().indexOf('.') + 4; + + pool.query('SELECT * FROM currency WHERE from_currency = $1 AND conv_currency = $2 AND date = $3', + [ + value, + pair, + new Date(data['time']).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) RETURNING *`, + [ + value, + pair, + data['rate'].toString().slice(0, point), + new Date(data['time']).toLocaleDateString() + ], + ); + }); + } + }) + ); +} + +function rotate_key(list, active) { + return active[0] = (active + 1) % list.length; +} + +module.exports = save_fiat; \ No newline at end of file