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

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

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 = [] // 清空请求列表
}
相关推荐
用户302822530681 小时前
别让 Agent 被 Webhook 叫醒就开工:实现一个幂等启动层
javascript
万少2 小时前
等不到 Apple 的折叠 iPhone,我用 DeepV4.1Flash + workBuddy 一句话自己造了一台
前端·javascript·后端
志尊宝2 小时前
Vue3 零基础每日笔记(009):watch 侦听器——数据一变就“做事“
vue.js·笔记·缓存
一夜枫林2 小时前
vue实现scroll-view上下滑动右侧左右滑动
前端·javascript·vue.js
志尊宝3 小时前
Vue3 零基础每日笔记(011):生命周期钩子——在正确的时间做正确的事
javascript·vue.js·笔记
YWL3 小时前
OpenLayers地图分享:URL参数同步+分享链接生成,让用户一键分享地图视角
前端·javascript·vue·openlayers
梦醒沉醉3 小时前
5、表达式与运算符
javascript
Q一件事5 小时前
ArcGIS中TypeError: can‘t multiply sequence by non-int of type ‘str‘错误
前端·javascript·arcgis
WeiXin_DZbishe5 小时前
基于springboot大学生提问箱系统-计算机毕设【课程设计】72593
javascript·vue.js·spring boot·vscode·python·node.js·php
FfHUCisI6 小时前
Go 内存分配器概览:从 TCMalloc 到三级缓存架构
缓存·架构·golang