query-registry
Version:
Query the npm registry for packuments, manifests, packages and download counts
55 lines (46 loc) • 1.09 kB
JavaScript
import unfetch from 'isomorphic-unfetch';
import lru from 'tiny-lru';
import { FetchError } from './errors.esm.js';
import { log } from './log.esm.js';
const maxItems = 250;
const fiveMinutesTTL = 5 * 60 * 1000;
const cache = /*#__PURE__*/lru(maxItems, fiveMinutesTTL);
async function fetch({
url,
headers,
cached = true
}) {
const cacheKey = `headers=${JSON.stringify(headers)};url=${url}`;
const cachedJSON = cache.get(cacheKey);
if (cached && cachedJSON) {
log('fetch: returning cached response: %O', {
cacheKey,
url,
cachedJSON
});
return cachedJSON;
}
const response = await unfetch(url, {
headers
});
if (!response.ok) {
log('fetch: request failed: %O', {
url,
headers,
status: response.statusText,
response
});
throw new FetchError(url, response);
}
const json = await response.json();
if (cached) {
cache.set(cacheKey, json);
}
log('fetch: returning fresh response: %O', {
url,
json
});
return json;
}
export { fetch };
//# sourceMappingURL=fetch.esm.js.map