-
Notifications
You must be signed in to change notification settings - Fork 432
/
fetch-npm-data.js
81 lines (70 loc) · 2.38 KB
/
fetch-npm-data.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import fetch from 'cross-fetch';
import { sleep } from './build-and-score-data';
const urlForPackage = (npmPkg, period = 'month') => {
return `https://api.npmjs.org/downloads/point/last-${period}/${npmPkg}`;
};
export const fetchNpmDataBulk = async (namesArray, period = 'month', attemptsCount = 0) => {
try {
const url = urlForPackage(namesArray.join(','), period);
const isMonthly = period === 'month';
const response = await fetch(url);
const downloadData = await response.json();
return namesArray.map(name => {
const pkgData = downloadData[name];
if (isMonthly && !pkgData?.downloads) {
console.warn(
`[NPM] ${name} doesn't exist on npm registry, add npmPkg to its entry or remove it!`
);
return { npm: null };
}
return {
name,
npm: isMonthly
? {
downloads: pkgData.downloads,
start: pkgData.start,
end: pkgData.end,
period,
}
: {
weekDownloads: pkgData?.downloads || 0,
},
};
});
} catch {
await sleep(1000 + 250 * attemptsCount, 2000 + 500 * attemptsCount);
console.log(`[NPM] Retrying fetch for ${namesArray} (${attemptsCount + 1})`);
return await fetchNpmDataBulk(namesArray, period, attemptsCount + 1);
}
};
export const fetchNpmData = async (pkgData, attemptsCount = 0) => {
const { npmPkg } = pkgData;
try {
const url = urlForPackage(npmPkg);
const response = await fetch(url);
const downloadData = await response.json();
if (!downloadData.downloads) {
console.warn(
`[NPM] ${npmPkg} doesn't exist on npm registry, add npmPkg to its entry or remove it!`
);
return { ...pkgData, npm: null };
}
const weekUrl = urlForPackage(npmPkg, 'week');
const weekResponse = await fetch(weekUrl);
const weekDownloadData = await weekResponse.json();
return {
...pkgData,
npm: {
downloads: downloadData.downloads,
weekDownloads: weekDownloadData.downloads,
start: downloadData.start,
end: downloadData.end,
period: 'month',
},
};
} catch {
await sleep(1000 + 250 * attemptsCount, 2000 + 500 * attemptsCount);
console.log(`[NPM] Retrying fetch for ${npmPkg} (${attemptsCount + 1})`);
return await fetchNpmData(pkgData, attemptsCount + 1);
}
};