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

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

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 = [] // 清空请求列表
}
相关推荐
起名时在学Aiifox17 小时前
Vue3 + Element Plus 表格排序实战:基于状态字段的智能排序方案
前端·javascript·vue.js·element plus
yzx99101317 小时前
基于Flask的智能语音增强系统模拟
前端·javascript·html
青衫码上行17 小时前
【Java Web学习 | 第14篇】JavaScript(8) -正则表达式
java·前端·javascript·学习·正则表达式
我的虾分发17 小时前
虾分发是一个键打包封装APP内测分发平台
javascript
天才熊猫君17 小时前
vue3 基于 el-table 的无限滚动自定义指令实现
前端·javascript
3秒一个大18 小时前
从代码示例看 ES8 中的 async/await:简化异步操作的利器
javascript
努力往上爬de蜗牛18 小时前
react native token失效 刷新机制
javascript·react native·react.js
Sailing18 小时前
🚀 Promise.then 与 async/await 到底差在哪?(这次彻底讲明白)
前端·javascript·面试
鹤鸣的日常18 小时前
Vue + element plus 二次封装表格
前端·javascript·vue.js·elementui·typescript
北慕阳18 小时前
速成Vue,自己看
前端·javascript·vue.js