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

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

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 = [] // 清空请求列表
}
相关推荐
demi_meng1 小时前
reactNative 遇到的问题记录
javascript·react native·react.js
千码君20162 小时前
React Native:从react的解构看编程众多语言中的解构
java·javascript·python·react native·react.js·解包·解构
RoboWizard3 小时前
扩容刚需 金士顿新款Canvas Plus存储卡
java·spring·缓存·电脑·金士顿
EndingCoder4 小时前
WebSocket实时通信:Socket.io
服务器·javascript·网络·websocket·网络协议·node.js
我胡为喜呀4 小时前
Vue3 中的 watch 和 watchEffect:如何优雅地监听数据变化
前端·javascript·vue.js
学无止境w4 小时前
高并发系统架构设计原则:无状态、水平扩展、异步化、缓存优先
缓存·系统架构
qqxhb5 小时前
系统架构设计师备考第45天——软件架构演化评估方法和维护
分布式·缓存·系统架构·集群·cdn·单体·已知未知评估
liangshanbo12156 小时前
React 19 vs React 18全面对比
前端·javascript·react.js
Never_Satisfied7 小时前
在 JavaScript 中,删除数组中内容为xxx的元素
java·前端·javascript
_菜鸟果果7 小时前
Vue3+echarts 3d饼图
前端·javascript·echarts