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

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

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 = [] // 清空请求列表
}
相关推荐
要开心吖ZSH13 分钟前
本地缓存方案选择指南:volatile、ConcurrentHashMap、Caffeine 怎么选?
缓存·caffeine·volatile·本地缓存
你挚爱的强哥17 分钟前
【exportExcel】单纯靠js不用任何其他第三方插件导出xls格式文件
开发语言·javascript·ecmascript
范什么特西18 分钟前
redis题目面渣重点
数据库·redis·缓存
今天的砖头有点烫手啊1 小时前
接口太慢?Spring Boot 缓存体系 @Cacheable 全链路拆解
spring boot·后端·缓存
大家的林语冰1 小时前
👉 尤雨溪再次成立新公司,同时官宣 Pinia 4 正式发布!
前端·javascript·vue.js
用户938515635071 小时前
从零在浏览器里跑 DeepSeek-R1:WebGPU + Transformer.js 全链路实战(二)
前端·javascript·typescript
szephyr2 小时前
腾讯云 ADP 智能体的 Skills 版本回滚总是回到旧配置,是缓存没清还是版本管理没开?
java·缓存·腾讯云
BD_Marathon2 小时前
部署Spark
大数据·javascript·spark
gis开发之家3 小时前
《Vue3 从入门到大神50篇》Vue3 源码详解(二十):生命周期钩子源码解析 —— onMounted / onUpdated 如何实现?
前端·javascript·前端框架·vue3·vue3源码
全栈项目管理程序猿3 小时前
ArcGIS JS 基础教程(9):天空盒与大气效果
javascript