fix: NbpService cache & tests fixes

This commit is contained in:
Piotr Dec 2024-05-23 23:55:33 +02:00
parent 1ae5dd9957
commit 52ff4a67b3
Signed by: stawros
GPG key ID: F89F27AD8F881A91
2 changed files with 28 additions and 7 deletions

View file

@ -13,6 +13,8 @@ import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* NBP exchange rates service
@ -26,12 +28,30 @@ public class NbpService {
private static final String URI_PATTERN = "/api/exchangerates/rates/c/{code}/{date}/";
private final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private final ConcurrentMap<String, RatesCache> cache = new ConcurrentHashMap<>(1);
public double getSellRate(String currency) {
return fetchData(currency, dtf.format(getFetchDate())).getRates().get(0).getAsk();
return getCurrency(currency).sell();
}
public double getBuyRate(String currency) {
return fetchData(currency, dtf.format(getFetchDate())).getRates().get(0).getBid();
return getCurrency(currency).buy();
}
private synchronized RatesCache getCurrency(String currency) {
var today = getFetchDate();
var cacheObject = cache.get(currency);
if (cacheObject == null || cacheObject.date().isBefore(today)) {
var fresh = fetchData(currency, dtf.format(today));
var rate = fresh.getRates().get(0);
cacheObject = new RatesCache(
LocalDate.parse(rate.getEffectiveDate(), dtf),
rate.getBid(),
rate.getAsk()
);
cache.put(fresh.getCode(), cacheObject);
}
return cacheObject;
}
/**