feat(theme): add repo card cache (#338)
This commit is contained in:
parent
3a73312414
commit
c4438afaa5
@ -1,4 +1,5 @@
|
||||
import type { MaybeRef } from 'vue'
|
||||
import { useLocalStorage } from '@vueuse/core'
|
||||
import { computed, ref, toValue, watch } from 'vue'
|
||||
|
||||
export interface GithubRepoInfo {
|
||||
@ -20,6 +21,15 @@ export interface GithubRepoInfo {
|
||||
} | null
|
||||
}
|
||||
|
||||
/**
|
||||
* 由于 github repo api 请求频率过高,vercel 免费额度有限,因此使用本地缓存。
|
||||
* 默认缓存 6 小时 时间
|
||||
*/
|
||||
const storage = useLocalStorage('github-repo', {} as Record<string, {
|
||||
info: GithubRepoInfo
|
||||
updatedAt: number
|
||||
}>)
|
||||
|
||||
export function useGithubRepo(repo: MaybeRef<string>) {
|
||||
const repoRef = computed(() => {
|
||||
const info = toValue(repo)
|
||||
@ -34,12 +44,25 @@ export function useGithubRepo(repo: MaybeRef<string>) {
|
||||
if (__VUEPRESS_SSR__ || !owner || !name)
|
||||
return
|
||||
|
||||
const key = `${owner}/${name}`
|
||||
const cached = storage.value[`${owner}/${name}`]
|
||||
if (cached && Date.now() - cached.updatedAt <= 21600000) {
|
||||
data.value = cached.info
|
||||
loaded.value = true
|
||||
return
|
||||
}
|
||||
|
||||
loaded.value = false
|
||||
const res = await fetch(`https://api.pengzhanbo.cn/github/repo/${owner}/${name}`)
|
||||
.then(res => res.json()) as GithubRepoInfo
|
||||
|
||||
data.value = res
|
||||
loaded.value = true
|
||||
|
||||
storage.value[key] = {
|
||||
info: res,
|
||||
updatedAt: Date.now(),
|
||||
}
|
||||
}
|
||||
|
||||
watch(repoRef, fetchData, { immediate: true })
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user