homepage/src/utils/proxy/cached-fetch.js

26 lines
571 B
JavaScript
Raw Normal View History

2022-08-24 10:44:35 +03:00
import cache from "memory-cache";
const defaultDuration = 5;
export default async function cachedFetch(url, duration, ua) {
2022-08-24 10:44:35 +03:00
const cached = cache.get(url);
// eslint-disable-next-line no-param-reassign
duration = duration || defaultDuration;
2022-08-24 10:44:35 +03:00
if (cached) {
return cached;
}
2022-09-07 16:53:24 +03:00
// wrapping text in JSON.parse to handle utf-8 issues
const options = {};
if (ua) {
options.headers = {
"User-Agent": ua,
};
}
const data = await fetch(url, options).then((res) => res.json());
2022-09-07 16:53:24 +03:00
cache.put(url, data, duration * 1000 * 60);
return data;
2022-08-24 10:44:35 +03:00
}