All files / src utils.ts

100% Statements 33/33
81.81% Branches 18/22
100% Functions 8/8
100% Lines 26/26

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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 844x   4x       7x     4x 6x         4x 152x 1x   151x                         4x   517x 308x 4x 13x   304x 304x 199x       209x   517x     4x 17x 17x   14x                                     4x 2300x 460x                
import hash from 'object-hash'
 
export function isAbsoluteURL(url: string) {
  // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  // by any combination of letters, digits, plus, period, or hyphen.
  return /^([a-z][a-z\d+-.]*:)?\/\//i.test(url);
}
 
export function combineURLs(baseURL: string, relativeURL?: string) {
  return relativeURL
    ? `${baseURL.replace(/\/+$/, '')}/${relativeURL.replace(/^\/+/, '')}`
    : baseURL;
}
 
export function buildFullPath(baseURL: string, requestedURL: string): string {
  if (baseURL && !isAbsoluteURL(requestedURL)) {
    return combineURLs(baseURL, requestedURL);
  }
  return requestedURL;
}
 
type DeepCopy<T> = T extends object
    ? T extends Array<infer Item>
      ? DeepCopy<Item>[]
      : {
          [K in keyof T]: T[K] extends object
            ? DeepCopy<T[K]>
            : T[K]
        }
    : T
 
export function deepCopy<T>(obj: T): DeepCopy<T> {
  let target: any;
  if (typeof obj === 'object' && obj !== null) {
    if (Array.isArray(obj)) {
      target = [];
      obj.forEach((elem) => target.push(deepCopy(elem)));
    } else {
      target = {};
      Object.keys(obj).forEach((key) => {
        target[key] = deepCopy((obj as Record<string, any>)[key]);
      });
    }
  } else {
    target = obj;
  }
  return target;
}
 
export function getType(obj: any): string {
  const type = typeof obj;
  if (type !== 'object') return type;
 
  return Object.prototype.toString.call(obj)
    .replace(/^\[object\s+(\S+)\]$/, '$1')
    .toLowerCase();
}
 
 
type NormalizedConfig = {
  params?: Record<string, any>
  data?: Record<string, any>
  url?: string
  baseURL?: string
  method?: string
}
 
/**
 * 获取请求的标识,相同的请求配置有相同的标识
 * @param config 经过标准化的ajax请求配置
 * @returns 该请求的hash key
 */
export function generateRequestHash(config: NormalizedConfig) {
  const { url = '', method = '', params = {}, data = {}, baseURL = '' } = config
  return hash({
    ...params,
    ...data,
    baseURL,
    url,
    method
  })
}