UNPKG

2.49 kBPlain TextView Raw
1import { DownloadPeriod } from '../types/download-period';
2import { DailyPackageDownloads } from '../types/downloads';
3import { assertValidPackageName } from '../utils/assert-valid-package-name';
4import { fetchDownloadsFromRegistry } from '../utils/fetch-downloads-from-registry';
5import { normalizeRawDownloadPeriod } from '../utils/normalize-download-period';
6
7/**
8 * `getDailyPackageDownloads` returns the number of downloads for a package
9 * for each day in a given time period.
10 *
11 * @param name - package name
12 * @param period - time period in which downloads happened (default: `last-week`)
13 * @param registryDownloadsAPI - URL of the registry's downloads API (default: npm registry)
14 * @param cached - accept cached responses (default: `true`)
15 *
16 * @example
17 * Get the day by day weekly downloads for package `query-registry` from the npm registry:
18 *
19 * ```typescript
20 * import { getDailyPackageDownloads } from 'query-registry';
21 *
22 * (async () => {
23 * const downloads = await getDailyPackageDownloads({ name: 'query-registry' });
24 *
25 * // Output: 'query-registry'
26 * console.log(downloads.package);
27 *
28 * // Output: 'number'
29 * console.log(typeof downloads.downloads[0].downloads);
30 * })();
31 * ```
32 *
33 * @example
34 * Get the day by day monthly downloads for package `query-registry` from the npm registry:
35 *
36 * ```typescript
37 * import { getDailyPackageDownloads } from 'query-registry';
38 *
39 * (async () => {
40 * const downloads = await getDailyPackageDownloads({ name: 'query-registry', period: 'last-month' });
41 *
42 * // Output: 'query-registry'
43 * console.log(downloads.package);
44 *
45 * // Output: 'number'
46 * console.log(typeof downloads.downloads[0].downloads);
47 * })();
48 * ```
49 *
50 * @see {@link DailyPackageDownloads}
51 * @see {@link DownloadPeriod}
52 * @see {@link npmRegistryDownloadsAPI}
53 * @see {@link https://github.com/npm/registry/blob/master/docs/download-counts.md#ranges}
54 */
55export async function getDailyPackageDownloads({
56 name,
57 period: rawDownloadPeriod,
58 registryDownloadsAPI,
59 cached,
60}: {
61 name: string;
62 period?: DownloadPeriod;
63 registryDownloadsAPI?: string;
64 cached?: boolean;
65}): Promise<DailyPackageDownloads> {
66 assertValidPackageName({ name });
67
68 const period = normalizeRawDownloadPeriod({ rawDownloadPeriod });
69 const endpoint = `/downloads/range/${period}/${name}`;
70 return fetchDownloadsFromRegistry({
71 endpoint,
72 registryDownloadsAPI,
73 cached,
74 });
75}