Skip to content

Commit

Permalink
fetch rates min
Browse files Browse the repository at this point in the history
  • Loading branch information
ceddybi committed Mar 28, 2024
1 parent 7fedfae commit 062cc7c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
12 changes: 9 additions & 3 deletions src/processors/kraken/rates/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[];
Expand Down Expand Up @@ -34,7 +34,11 @@ export const fetchRates = async (pairs: string, cache = false): Promise<PairRate
const rates = await Promise.all(
pairs.split(',').map((pair) => 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) => {
Expand Down Expand Up @@ -74,6 +78,8 @@ export const fetchRates = async (pairs: string, cache = false): Promise<PairRate

const rates = await Promise.all(pairs.split(',').map(getRates));

log('rates', rates);

return rates;
} catch (error) {
console.log('Error getting store rates:', error);
Expand All @@ -87,7 +93,7 @@ export const fetchRatesSaveToCache = async (pairs: string): Promise<any> => {
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);
Expand Down
19 changes: 15 additions & 4 deletions src/processors/shared.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -12,19 +15,27 @@ export class RatesCache {
this.redis = new Redis(REDIS_URL);
}

async getPair(pair) {
async getPair(pair: string): Promise<PairRate> {
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<boolean> {
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;
}
}
}

0 comments on commit 062cc7c

Please sign in to comment.