unpkg/server/utils/getNpmPackageInfo.js

58 lines
1.7 KiB
JavaScript
Raw Normal View History

2018-07-16 17:17:00 +00:00
const cache = require("./cache");
2018-02-18 02:00:56 +00:00
const createMutex = require("./createMutex");
const fetchNpmPackageInfo = require("./fetchNpmPackageInfo");
const notFound = "PackageNotFound";
const mutex = createMutex((packageName, callback) => {
2018-07-16 17:17:00 +00:00
const key = `packageInfo2-${packageName}`;
cache.get(key, (error, value) => {
if (error) {
callback(error);
} else if (value != null) {
2018-07-16 17:17:00 +00:00
callback(null, value === notFound ? null : JSON.parse(value));
} else {
fetchNpmPackageInfo(packageName).then(
value => {
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-07-16 17:17:00 +00:00
cache.setex(key, 300, notFound, () => {
callback(null, null);
});
} else {
2018-07-16 17:17:00 +00:00
// Cache valid package info for 1 minute. In the worst case,
// new versions won't be available for 1 minute.
cache.setnx(key, JSON.stringify(value), (error, reply) => {
if (reply === 1) cache.expire(key, 60);
callback(null, value);
});
}
},
error => {
// Do not cache errors.
2018-07-16 17:17:00 +00:00
cache.del(key);
callback(error);
}
);
}
});
2018-02-18 02:00:56 +00:00
});
function getNpmPackageInfo(packageName) {
2018-05-21 22:44:00 +00:00
return new Promise((resolve, reject) => {
mutex(packageName, (error, value) => {
2018-05-21 22:44:00 +00:00
if (error) {
reject(error);
} else {
resolve(value);
2018-05-21 22:44:00 +00:00
}
});
2018-02-18 02:00:56 +00:00
});
}
module.exports = getNpmPackageInfo;