返回 AiToEarn
useGitHubStars.ts
根目录 / project / aitoearn-web / src / app / layout / shared / hooks / useGitHubStars.ts
1 /**
2 * useGitHubStars - 获取 GitHub 仓库 star 数量(每天缓存一次)
3 */
4
5 import { useEffect } from 'react'
6 import { useShallow } from 'zustand/react/shallow'
7 import { useSystemStore } from '@/store/system'
8 import { GITHUB_REPO } from '../constants'
9
10 const ONE_DAY_MS = 24 * 60 * 60 * 1000
11
12 /**
13 * 获取 GitHub 仓库的 star 数量
14 * @returns star 数量字符串(如 "9.5k")
15 */
16 export function useGitHubStars() {
17 const { githubStars, githubStarsUpdatedAt } = useSystemStore(
18 useShallow(s => ({
19 githubStars: s.githubStars,
20 githubStarsUpdatedAt: s.githubStarsUpdatedAt,
21 })),
22 )
23
24 useEffect(() => {
25 if (Date.now() - githubStarsUpdatedAt < ONE_DAY_MS)
26 return
27
28 fetch(`https://api.github.com/repos/${GITHUB_REPO}`)
29 .then(res => res.json())
30 .then((data) => {
31 if (data.stargazers_count) {
32 const count = data.stargazers_count
33 const formatted = count >= 1000 ? `${(count / 1000).toFixed(1)}k` : count.toString()
34 useSystemStore.getState().setGitHubStars(formatted)
35 }
36 })
37 .catch(() => {
38 // 失败时保持缓存值
39 })
40 }, [githubStarsUpdatedAt])
41
42 return githubStars
43 }
44
44 lines TYPESCRIPT