All files / src cancelLastSameRequest.ts

100% Statements 20/20
100% Branches 8/8
80% Functions 4/5
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43          1x   1x   1x 12x 12x 12x     1x 204x 12x 12x 12x                       1x 12x 12x 6x 6x   12x          
/**
 * 取消相同URL和method的上一个未结束请求,主要目的是防止页面切换时串数据,比如tab切换
 * 且只针对get请求
 */
// import hash from 'object-hash'
export { generateRequestHash  } from "./utils"
 
const cancellerCache: Record<string, Record<string, any>> = {}
 
export function addRequestCanceler(url: string, hash: string, cancelFn: () => void) {
  const urlCache = cancellerCache[url] || {}
  urlCache[hash] = cancelFn
  cancellerCache[url] = urlCache
}
 
export function clearCancelerByHash(url: string, hash: string) {
  if (cancellerCache[url] && cancellerCache[url][hash]) {
    Reflect.deleteProperty(cancellerCache[url], hash)
    if (Object.keys(cancellerCache[url]).length === 0) {
      Reflect.deleteProperty(cancellerCache, url)
    }
  }
}
 
 
// export function checkIfHasURLCanceler(url: string): boolean {
//   if (!cancellerCache[url]) return false
//   if (Object.keys(cancellerCache[url]).length === 0) return false
//   return true
// }
 
export function execCanceler(url: string) {
  const cancelers = cancellerCache[url] || {}
  Object.entries(cancelers).forEach(([key, fn]) => {
    fn()
    Reflect.deleteProperty(cancelers, key)
  })
  Reflect.deleteProperty(cancellerCache, url)
}
 
// export function getCachedCanceler(hashKey: string) {
//   return cancellerCache[hashKey]
// }