unpkg/modules/utils/getNpmPackageInfo.js

44 lines
1.3 KiB
JavaScript
Raw Normal View History

2019-01-06 00:50:05 +00:00
import LRUCache from 'lru-cache';
2019-01-06 00:50:05 +00:00
import fetchNpmPackageInfo from './fetchNpmPackageInfo';
2019-01-06 00:50:05 +00:00
const maxMegabytes = 40; // Cap the cache at 40 MB
const maxLength = maxMegabytes * 1024 * 1024;
const oneSecond = 1000;
const oneMinute = 60 * oneSecond;
2018-12-17 22:02:59 +00:00
2019-01-06 00:50:05 +00:00
const cache = new LRUCache({
max: maxLength,
maxAge: oneMinute,
length: Buffer.byteLength
});
const notFound = '';
export default function getNpmPackageInfo(packageName) {
2018-07-16 19:05:02 +00:00
return new Promise((resolve, reject) => {
const key = `npmPackageInfo-${packageName}`;
2018-12-17 23:57:44 +00:00
const value = cache.get(key);
2018-07-16 17:17:00 +00:00
2018-12-17 23:57:44 +00:00
if (value != null) {
resolve(value === notFound ? null : JSON.parse(value));
} else {
2019-01-06 00:50:05 +00:00
fetchNpmPackageInfo(packageName).then(info => {
if (info == null) {
2018-12-17 23:57:44 +00:00
// Cache 404s for 5 minutes. This prevents us from making
// unnecessary requests to the registry for bad package names.
// In the worst case, a brand new package's info will be
// available within 5 minutes.
2019-01-06 00:50:05 +00:00
cache.set(key, notFound, oneMinute * 5);
2018-12-17 23:57:44 +00:00
resolve(null);
} else {
// Cache valid package info for 1 minute. In the worst case,
// new versions won't be available for 1 minute.
2019-01-06 00:50:05 +00:00
cache.set(key, JSON.stringify(info), oneMinute);
resolve(info);
2018-12-17 23:57:44 +00:00
}
}, reject);
}
2018-02-18 02:00:56 +00:00
});
}