All files / src index.ts

100% Statements 21/21
100% Branches 6/6
100% Functions 3/3
100% Lines 21/21

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 431x 1x 1x 1x 1x             177x     1x 177x 177x     177x 177x 177x   177x 177x 1062x 1062x       177x     177x   177x     177x   177x    
import axios from 'axios'
import { wxAdatper } from './adapters/index'
import addCompatibleMethods from './compatibleMethods'
import { addInstanceExtendMethod, proxyAjaxCanceler, proxyAxiosMethods } from './helpers'
import { generateMethod } from './methods'
import type {AjaxInstance, AjaxOption, AxiosMethods, RequestMethods} from './types'
import { callCancellerByCancelKey } from './canceller'
 
declare const wx: any;
 
function isWxapp(): boolean {
  return typeof wx !== 'undefined' && typeof wx.request === 'function';
}
 
export default function initAjax<CusOpts extends object, ResDataShape extends object = any>(options: AjaxOption & CusOpts): AjaxInstance<CusOpts, ResDataShape> {
  const ajax = {} as AjaxInstance<CusOpts, ResDataShape>;
  ajax.$options = options;
 
  // 检测wx如果没有自定义的适配器,则使用默认适配器
  const adapter = ajax.$options.adapter || (isWxapp() ? wxAdatper : undefined);
  ajax.$options.adapter = adapter
  ajax.$engine = axios.create();
 
  const requestMethods: AxiosMethods[] = ['POST', 'PUT', 'PATCH', 'DELETE', 'GET', 'HEAD']
  requestMethods.forEach((name: AxiosMethods) => {
    const queryMethods = name.toLocaleLowerCase() as RequestMethods
    ajax[queryMethods] = generateMethod<CusOpts, ResDataShape>(ajax, name)
  })
 
  // 挂载请求的手动取消函数
  proxyAjaxCanceler(ajax)
 
  // 把ajax实例上的'request', 'interceptors'方法代理到axios上去
  proxyAxiosMethods(ajax, ajax.$engine);
 
  addCompatibleMethods(ajax)
 
  // 添加extend方法,用于扩展ajax实例
  addInstanceExtendMethod(ajax);
 
  return ajax;
}