unpkg/server/utils/getPackageInfo.js

58 lines
1.7 KiB
JavaScript
Raw Normal View History

2018-02-18 02:00:56 +00:00
const createCache = require("./createCache");
const createMutex = require("./createMutex");
2018-05-21 22:44:00 +00:00
const fetchPackageInfo = require("./fetchPackageInfo");
2018-04-04 19:06:17 +00:00
const packageInfoCache = createCache("packageInfo");
2018-05-21 22:44:00 +00:00
const packageNotFound = "PackageNotFound";
// This mutex prevents multiple concurrent requests to
// the registry for the same package info.
2017-11-08 18:14:46 +00:00
const fetchMutex = createMutex((packageName, callback) => {
2017-11-08 16:57:15 +00:00
fetchPackageInfo(packageName).then(
2018-04-04 19:06:17 +00:00
value => {
2017-11-08 16:57:15 +00:00
if (value == null) {
// 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.
2018-05-21 22:44:00 +00:00
packageInfoCache.set(packageName, packageNotFound, 300, () => {
2018-02-18 02:00:56 +00:00
callback(null, value);
});
2017-11-08 16:57:15 +00:00
} else {
// Cache valid package info for 1 minute.
2018-04-04 19:06:17 +00:00
packageInfoCache.set(packageName, value, 60, () => {
2018-02-18 02:00:56 +00:00
callback(null, value);
});
2017-11-08 16:57:15 +00:00
}
},
2018-04-04 19:06:17 +00:00
error => {
2017-11-08 16:57:15 +00:00
// Do not cache errors.
2018-04-04 19:06:17 +00:00
packageInfoCache.del(packageName, () => {
2018-02-18 02:00:56 +00:00
callback(error);
});
}
2018-02-18 02:00:56 +00:00
);
});
2018-05-21 22:44:00 +00:00
function getPackageInfo(packageName) {
return new Promise((resolve, reject) => {
packageInfoCache.get(packageName, (error, value) => {
if (error) {
reject(error);
} else if (value != null) {
resolve(value === packageNotFound ? null : value);
} else {
fetchMutex(packageName, (error, value) => {
if (error) {
reject(error);
} else {
resolve(value);
}
});
}
});
2018-02-18 02:00:56 +00:00
});
}
2018-02-18 02:00:56 +00:00
module.exports = getPackageInfo;