2022-08-24 10:44:35 +03:00
|
|
|
import cache from "memory-cache";
|
|
|
|
|
2022-10-09 20:05:28 -07:00
|
|
|
const defaultDuration = 5;
|
|
|
|
|
2022-08-24 10:44:35 +03:00
|
|
|
export default async function cachedFetch(url, duration) {
|
|
|
|
const cached = cache.get(url);
|
|
|
|
|
2022-10-09 20:05:28 -07:00
|
|
|
// 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
|
|
|
|
2024-02-01 00:42:22 -08:00
|
|
|
// wrapping text in JSON.parse to handle utf-8 issues
|
|
|
|
const data = JSON.parse(await fetch(url).then((res) => res.text()));
|
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
|
|
|
}
|