简单的接口缓存机制,避免了重复请求,同时支持缓存过期时间。

简单的接口缓存机制,避免了重复请求,同时支持缓存过期时间。

typescript 复制代码
const CACHE_LIFETIME = 30

interface ApiCacheOptions {
  /** 缓存时长(秒) */
  cacheLifetime?: number
}

type CacheStatus = 'notStarted' | 'loading' | 'finished' | 'error'

interface CacheItem<T = any> {
  status: CacheStatus
  result: T | null
  requestList: ((res: T | Error) => void)[]
  timer?: NodeJS.Timeout
}

const resultCache = new Map<string, CacheItem>()

export async function apiCache<T>(
  apiKey: string,
  func: () => Promise<T>,
  options?: ApiCacheOptions
): Promise<T> {
  const cacheLifetime = options?.cacheLifetime ?? CACHE_LIFETIME
  const item = getItem<T>(apiKey)

  if (item.status === 'finished') {
    return item.result as T
  }

  if (item.status === 'loading') {
    return new Promise<T>((resolve, reject) => {
      addSubscriber(apiKey, (res) => {
        if (res instanceof Error) reject(res)
        else resolve(res)
      })
    })
  }

  try {
    item.status = 'loading'
    item.result = await func()
    item.status = 'finished'

    // 设置缓存过期
    item.timer = setTimeout(() => {
      removeItem(apiKey)
    }, cacheLifetime * 1000)

    onAccessTokenFetched(apiKey, item.result)
    return item.result
  } catch (error) {
    item.status = 'error'
    onAccessTokenFetched(apiKey, error as Error) // 传递错误给订阅者
    throw error
  }
}

function getItem<T>(key: string): CacheItem<T> {
  if (!resultCache.has(key)) {
    resultCache.set(key, { status: 'notStarted', result: null, requestList: [] })
  }
  return resultCache.get(key) as CacheItem<T>
}

function removeItem(key: string) {
  if (resultCache.has(key)) {
    const item = resultCache.get(key)
    if (item?.timer) clearTimeout(item.timer) // 清理定时器
    resultCache.delete(key) // 彻底删除,防止内存泄漏
  }
}

function addSubscriber<T>(key: string, callback: (res: T | Error) => void) {
  const item = getItem<T>(key)
  item.requestList.push(callback)
}

function onAccessTokenFetched<T>(key: string, result: T | Error) {
  const item = getItem<T>(key)
  item.requestList.forEach((callback) => callback(result))
  item.requestList = [] // 清空请求列表
}
相关推荐
Z_Wonderful1 小时前
在 Next.js 中,使用 [id] 或 public 作为文件夹或文件名是两种完全不同的概念,分别对应 动态路由 和 静态资源托管
javascript·网络·chrome
刘~浪地球1 小时前
Redis 从入门到精通(四):字符串操作详解
数据库·redis·缓存
xhuiting2 小时前
Redis专题(二)
redis·缓存
妖萌妹儿3 小时前
postman怎么做参数化批量测试,测试不同输入组合
开发语言·javascript·postman
Zk.Sun3 小时前
【RK3588 Mali610 适配 Qt6 】
前端·javascript·vue.js
不想吃菠萝3 小时前
vue3+ts 使用postcss-pxtorem依赖进行rem适配
前端·javascript·vue.js·postcss
kyriewen114 小时前
本地存储全家桶:从localStorage到IndexedDB,把数据塞进用户浏览器
开发语言·前端·javascript·ecmascript·html5
Rysxt_4 小时前
Vue 组件穿透(透传)完全指南:从背景到实战
前端·javascript·vue.js
束尘4 小时前
Vue3 + Element Plus 实现 ZIP 压缩包在线预览(支持图片插入 / 文件预览)
前端·javascript·vue.js
一只小阿乐5 小时前
js流式模式输出 函数模式使用
开发语言·javascript·ai·vue·agent·流式数据·node 服务