koboprice/lib/bookPriceFor.js

46 lines
1 KiB
JavaScript
Raw Permalink Normal View History

2024-07-14 22:36:08 +03:00
import { bookUrl } from "./bookUrl";
2024-07-15 20:52:41 +03:00
import { extractPrice } from "./extractPrice";
2024-07-14 22:36:08 +03:00
import { getRate } from "./rates";
2024-07-15 14:45:38 +03:00
import { convertPrice } from "./convertPrice";
2024-07-14 22:36:08 +03:00
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;
}
2024-07-15 20:52:41 +03:00
const countryPrice = await extractPrice(url);
2024-07-14 22:36:08 +03:00
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:45:38 +03:00
convertedPrice = await convertPrice(
2024-07-15 14:32:15 +03:00
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;
};