2024-07-14 22:36:08 +03:00
|
|
|
import { bookUrl } from "./bookUrl";
|
|
|
|
import { extractPriceFrom } from "./extractPriceFrom";
|
|
|
|
import { getRate } from "./rates";
|
|
|
|
import { cacheBookPrice, getBookPrice } from "./cache";
|
|
|
|
import { format, isToday } from "date-fns";
|
|
|
|
|
|
|
|
export const bookPriceFor = async (country) => {
|
|
|
|
l("looking price for", country.countryCode);
|
|
|
|
|
|
|
|
const url = bookUrl(country.countryCode);
|
|
|
|
|
|
|
|
const fromCache = getBookPrice(url);
|
|
|
|
|
|
|
|
if (fromCache && isToday(fromCache.cachedAt)) {
|
|
|
|
l("found book price in cache", fromCache);
|
|
|
|
return fromCache;
|
|
|
|
}
|
|
|
|
|
|
|
|
const countryPrice = await extractPriceFrom(url);
|
|
|
|
|
|
|
|
let convertedPrice;
|
|
|
|
|
|
|
|
if (countryPrice) {
|
2024-07-15 14:32:15 +03:00
|
|
|
l("found price", countryPrice, url);
|
2024-07-14 22:36:08 +03:00
|
|
|
const rate = await getRate(country.currencyCode);
|
2024-07-15 14:32:15 +03:00
|
|
|
convertedPrice = await convertedPrice(
|
|
|
|
countryPrice,
|
|
|
|
country.currencyCode,
|
|
|
|
rate,
|
|
|
|
);
|
2024-07-14 22:36:08 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
const newPrice = {
|
|
|
|
...country,
|
|
|
|
countryPrice,
|
|
|
|
convertedPrice,
|
|
|
|
url,
|
|
|
|
cachedAt: format(new Date(), "yyyy-MM-dd"),
|
|
|
|
};
|
|
|
|
|
|
|
|
cacheBookPrice(newPrice, url);
|
|
|
|
|
|
|
|
return newPrice;
|
|
|
|
};
|