diff --git a/src/components/RecentDownloads.tsx b/src/components/RecentDownloads.tsx
index d692991..1964add 100644
--- a/src/components/RecentDownloads.tsx
+++ b/src/components/RecentDownloads.tsx
@@ -14,7 +14,7 @@ type RecentDownloadsContentProps = {
export function RecentDownloads({ pkgName, version }: RecentDownloadsContentProps) {
const { data: res, isLoading } = useRecentDownloads(pkgName, version);
- if (isLoading) {
+ if (isLoading || !res) {
return ;
}
diff --git a/src/hooks/useRecentDownloads.ts b/src/hooks/useRecentDownloads.ts
index 850168d..7cde98c 100644
--- a/src/hooks/useRecentDownloads.ts
+++ b/src/hooks/useRecentDownloads.ts
@@ -2,6 +2,8 @@ import { REGISTRY } from '@/config';
import dayjs from 'dayjs';
import useSwr from 'swr';
+const DEFAULT_RANGE = 7;
+
type DownloadRes = {
downloads: { day: string; downloads: number; }[];
versions?: {
@@ -9,16 +11,39 @@ type DownloadRes = {
};
};
-// https://registry.npmmirror.com/downloads/range/2023-01-01:2023-12-28/antd
-function getUrl(pkgName: string, range = 8) {
+// https://registry.npmmirror.com/downloads/range/2023-01:2023-01/antd
+// npmmirror 只支持按月维度返回
+function getUrl(pkgName: string, range: number) {
const today = dayjs();
const todayStr = today.format('YYYY-MM-DD');
const lastWeekStr = today.subtract(range, 'day').format('YYYY-MM-DD');
return `${REGISTRY}/downloads/range/${lastWeekStr}:${todayStr}/${pkgName}`;
};
-export const useRecentDownloads = (pkgName: string, version: string, range?: number) => {
+
+function normalizeRes(res: DownloadRes, version: string, range: number): DownloadRes {
+ // 根据 range,获取最近 range 天的数据
+ const downloads = res.downloads.slice(-range);
+ // 单个版本可能没有数据,需要做 leftPad
+ const versions = (new Array(range)).fill(0).map((_, index) => {
+ const day = dayjs().subtract(range - index - 1, 'day').format('YYYY-MM-DD');
+ const download = res.versions?.[version]?.find((item) => item.day === day);
+ return download || {
+ day,
+ downloads: 0
+ };
+ });
+
+ return {
+ downloads,
+ versions: {
+ [version]: versions,
+ }
+ };
+}
+export const useRecentDownloads = (pkgName: string, version: string, range: number = DEFAULT_RANGE) => {
return useSwr(`recent_downloads: ${pkgName}_${version}`, async () => {
return fetch(`${getUrl(pkgName, range)}`)
- .then((res) => res.json());
+ .then((res) => res.json())
+ .then(res => normalizeRes(res, version, range));
});
};