From 82ad228c1a1cbb49282e7c512abffe3772aec819 Mon Sep 17 00:00:00 2001 From: Redume Date: Thu, 2 Jan 2025 21:19:08 +0300 Subject: [PATCH] feat(collect-currency): Bringing back cryptocurrency rate collection --- collect-currency/main.js | 3 +- collect-currency/save_crypto.js | 58 +++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 collect-currency/save_crypto.js diff --git a/collect-currency/main.js b/collect-currency/main.js index 156736d..b81586a 100644 --- a/collect-currency/main.js +++ b/collect-currency/main.js @@ -3,6 +3,7 @@ const config = require('../shared/config/src/main.js')(); const cron = require('cron-validator'); const save_fiat = require('./save_fiat'); +const save_crypto = require('./save_crypto'); const logger = require('../shared/logger/src/main.js'); async function validateSchedule(schedule) { @@ -16,7 +17,7 @@ async function initialize() { } async function runTasks() { - await Promise.all([save_fiat()]); + await Promise.all([save_fiat(), save_crypto()]); } async function main() { diff --git a/collect-currency/save_crypto.js b/collect-currency/save_crypto.js new file mode 100644 index 0000000..ffa7acc --- /dev/null +++ b/collect-currency/save_crypto.js @@ -0,0 +1,58 @@ +const pool = require('../shared/database/src/postgresql.js'); +const axios = require('axios'); +const config = require('../shared/config/src/main.js')(); +const logger = require('../shared/logger/src/main.js'); + +async function save_crypto() { + if (!config['currency']['collecting']['crypto']) return; + + config['currency']['crypto'].forEach((value) => + config['currency']['crypto'].forEach(async (pair) => { + if (value === pair) return; + + await axios.get('https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest', { + timeout: 3000, + params: { + 'symbol': value, + 'convert': pair, + }, + headers: { + 'X-CMC_PRO_API_KEY': config['currency']['collecting']['crypto_apikey'], + } + }) + .then(async (res) => { + const data = res['data']['data'][value]['quote'][pair]; + + logger.debug(JSON.stringify(data, null, 4)); + + const point = data['price'].toString().indexOf('.') + 4; + + const db = await pool.query( + 'SELECT * FROM currency WHERE ' + + 'from_currency = $1 AND conv_currency = $2 AND date = $3', + [ + value, + pair, + new Date(data['last_updated']).toISOString().substring(0, 10), + ], + ); + + 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['price'].toString().slice(0, point), + new Date(data['last_updated']).toISOString().substring(0, 10), + ], + ); + }) + .catch((err) => { + logger.error(err); + }); + }) + ); +} + +module.exports = save_crypto; \ No newline at end of file