From 062cc7c4b3cd87ec90d320959ec9a8f65c502704 Mon Sep 17 00:00:00 2001 From: ceddybi Date: Wed, 27 Mar 2024 20:46:08 -0400 Subject: [PATCH] fetch rates min --- src/processors/kraken/rates/index.ts | 12 +++++++++--- src/processors/shared.ts | 19 +++++++++++++++---- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/src/processors/kraken/rates/index.ts b/src/processors/kraken/rates/index.ts index 6a95f2c..1cdb608 100644 --- a/src/processors/kraken/rates/index.ts +++ b/src/processors/kraken/rates/index.ts @@ -4,7 +4,7 @@ import {PairRate, RatesCache} from '../../shared'; // [cron] getAllTransactions -> settle import axios from 'axios'; import {isEmpty} from 'lodash'; -import {verbose} from 'roadman'; +import {log} from '@roadmanjs/logs'; interface PublicTickerResponse { error: any[]; @@ -34,7 +34,11 @@ export const fetchRates = async (pairs: string, cache = false): Promise ratesCache.getPair(pair)) ); - return rates as any; + + if (!rates.some((rate) => !rate) && !rates.some((rate) => Number.isNaN(rate.rate))) { + log('rates cache', rates); + return rates as any; + } } const getRates = async (pairrr: string) => { @@ -74,6 +78,8 @@ export const fetchRates = async (pairs: string, cache = false): Promise => { const rates = await fetchRates(pairs); if (!isEmpty(rates)) { const savedPairs = await rates.map(async (rate) => cache.savePair(rate.pair, rate)); - verbose('savedPairs', savedPairs.length); + log('savedPairs', savedPairs.length); } } catch (error) { console.log('error fetchRatesSaveToCache', error); diff --git a/src/processors/shared.ts b/src/processors/shared.ts index 0e150b6..b40f477 100644 --- a/src/processors/shared.ts +++ b/src/processors/shared.ts @@ -1,6 +1,9 @@ import {REDIS_URL} from 'roadman'; import Redis from 'ioredis'; +const ratesExpireMin = !Number.isNaN(+process.env.RATES_EXPIRE_MIN) + ? +process.env.RATES_EXPIRE_MIN + : 5; export interface PairRate { pair: string; rate: number; @@ -12,19 +15,27 @@ export class RatesCache { this.redis = new Redis(REDIS_URL); } - async getPair(pair) { + async getPair(pair: string): Promise { return new Promise((resolve) => { this.redis.get(pair, (err, result) => { if (err) { resolve(null); } else { - resolve(JSON.parse(result)); + resolve(JSON.parse(result) as PairRate); } }); }); } - async savePair(pair, value: any) { - return this.redis.set(pair, JSON.stringify(value)); + async savePair(pair: string, value: PairRate): Promise { + try { + if (!value || !value.pair || !value.rate) { + return false; + } + await this.redis.set(pair, JSON.stringify(value), 'EX', 60 * ratesExpireMin); + return true; + } catch (error) { + return false; + } } }