Skip to content

Commit

Permalink
fix: recent downloads (#70)
Browse files Browse the repository at this point in the history
> #68 

* 修复新发版本时,界面数据展示异常


![image](https://github.com/cnpm/cnpmweb/assets/5574625/946bc2dd-ad81-421a-b536-b0b066dcd08a)
  • Loading branch information
elrrrrrrr authored Jan 11, 2024
1 parent 47d10da commit 608cc3a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/components/RecentDownloads.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <Empty description="暂无数据" />;
}

Expand Down
33 changes: 29 additions & 4 deletions src/hooks/useRecentDownloads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,48 @@ import { REGISTRY } from '@/config';
import dayjs from 'dayjs';
import useSwr from 'swr';

const DEFAULT_RANGE = 7;

type DownloadRes = {
downloads: { day: string; downloads: number; }[];
versions?: {
[version: string]: { day: string; downloads: number; }[];
};
};

// 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<DownloadRes>(`recent_downloads: ${pkgName}_${version}`, async () => {
return fetch(`${getUrl(pkgName, range)}`)
.then((res) => res.json());
.then((res) => res.json())
.then(res => normalizeRes(res, version, range));
});
};

0 comments on commit 608cc3a

Please sign in to comment.