zoukankan      html  css  js  c++  java
  • 中间件-缓存加载函数

    /*
    缓存加载函数
    cacheLen:最多缓存多少个接口
    id:唯一值
    name:方法名
    syncFunc:加载函数
     */
    // 缓存最近的20个接口
    const methodCacheArr = []
    let cacheLen = 20
    try {
      const arr=JSON.parse(localStorage.getItem('queryNoError'))
      arr.forEach(function (item) {
        methodCacheArr.push(item)
      })
      cacheLen=arr.length+20;
    }catch (e) {
      
    }
    
    function getCacheIndex (val, key) {
      let has = -1
      for (let i = methodCacheArr.length - 1; i >= 0; i--) {
        if (val === methodCacheArr[i][key]) {
          has = i
          break
        }
      }
      return has
    }
    
    export function getCache (name) {
      const has = getCacheIndex(name, 'name')
      if (has > -1) {
        return methodCacheArr[has].res
      } else {
        return null
      }
    }
    
    export function delCache (name) {
      const has = getCacheIndex(name, 'name')
      if (has > -1) {
        methodCacheArr.splice(has, 1)
      }
    }
    
    export async function limitCache ({id, name, useCache,queryNoError}, syncFunc) {
      const has = getCacheIndex(id, 'id')
    
      if (useCache && has > -1) {
        if(typeof useCache !== 'number'){
          useCache=300;
        }
        if (useCache * 1000 + methodCacheArr[has].time > +new Date()) {
          return methodCacheArr[has].res
        }
      }
      let res = await syncFunc()
      //更新缓存
      if (res && res.flag === 'S') {
        if (has > -1) {
          methodCacheArr.splice(has, 1)
        }
        methodCacheArr.push({
          id: id,
          queryNoError:queryNoError,
          name: name,
          time: +new Date(),
          res: res
        })
        if (methodCacheArr.length > cacheLen) {
          methodCacheArr.splice(0, 1)
        }
        if(queryNoError){
          const arr=methodCacheArr.filter(function (item) {
            return item.queryNoError;
          })
          if (arr.length > 20) {
            arr.splice(0, 1)
          }
          localStorage.setItem('queryNoError',JSON.stringify(arr))
        }
      }else if(has > -1&&queryNoError){
        //兼容查询失败的情况
        return methodCacheArr[has].res;
      }
      return res
    }
    

      

  • 相关阅读:
    iOS7.0后隐藏状态栏(UIStatusBar)
    UITableView
    UIScrollView
    [IOS]edgesForExtendedLayout、automaticallyAdjustsScrollViewInsets
    UISearchController
    App开发流程之通用宏定义及头文件
    App开发流程之Xcode配置和本地化
    App开发流程之源代码Git管理
    App开发流程之增加预编译头文件
    App开发流程之配置Info.plist文件
  • 原文地址:https://www.cnblogs.com/caoke/p/14000416.html
Copyright © 2011-2022 走看看