zhaoxiaoqiang1
2026-01-04 f1d30d03186c79ca2cbcfe60d6d2ce7d73fba97b
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
/*
 * @Author: lixiong
 * @Date: 2019-09-06 14:13:27
 * @Last Modified by: lixiong
 * @Last Modified time: 2019-10-15 09:44:41
 */
 
// 基础请求封装
export default class BaseFetch {
  /**
   * constructor 构造函数
   * @param {Object} conf 实例全局配置,配置项基本同 defaultConf
   */
  constructor(conf = {}) {
    this.defaultConf = {
      timeout: 30000,
      method: 'post',
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    }
 
    this.specialBodyKeys = ['body', 'method', 'headers']
    this.init(conf)
  }
 
  /**
   * 初始化,合并配置
   * @param {Object} conf 全局配置
   */
  init(conf) {
    const { defaultConf } = this
    this.conf = Object.assign({}, { ...defaultConf }, { ...conf })
  }
 
  /**
   * post 请求处理
   * @param {String} api 接口地址
   * @param {Object|String} body 请求参数
   * @param {Object} conf 请求配置信息
   */
  toPost(api, body = {}, conf = {}) {
    return this.toFetch(api, body, { method: 'post', ...conf })
  }
 
  /**
   * get 请求处理
   * @param {String} api 接口地址
   * @param {Object|String} body 请求参数
   * @param {Object} conf 请求配置信息
   */
  toGet(api, body = {}, conf = {}) {
    return this.toFetch(api, body, { method: 'get', ...conf })
  }
 
  /**
   * mixConf 合并配置项
   * @param {Object} conf 请求配置项
   * @param {Object} body 参数或包含参数的配置项 @example {data: {name: 'someone'}}
   * @param {Object} conf 请求配置信息
   */
  mixConf(api, body = {}, conf = {}) {
    const { specialBodyKeys } = this
    let mixConf = { ...this.conf, ...conf }
 
    if (typeof body === 'string') {
      mixConf = { ...mixConf, body }
    }
    if (typeof body === 'object') {
      // body包含配置项,则body为配置信息
      if (Object.keys(body).some(key => specialBodyKeys.includes(key))) {
        mixConf = { ...mixConf, ...body }
      } else {
        mixConf = { ...mixConf, body }
      }
    }
 
    const { method, body: mixBody, headers, ...other } = mixConf
    const url = this.getUrl(api, mixConf)
    let result =
      headers === false
        ? { url, method, ...other }
        : { url, method, headers, ...other }
 
    if (method.toLocaleLowerCase() !== 'get') {
      result = { ...result, body: this.getBody(mixConf) }
    }
    return result
  }
 
  /**
   * joinPath拼接路径,去重中间重复连接符/
   * @param {Array} pathArr 路径数组
   * @param {Boolean} isReplaceFirst 是否去除第一个路径前的/
   */
  joinPath(pathArr, isReplaceFirst = false) {
    return pathArr.reduce((pre, curr, index) => {
      const nextPath = curr.replace(/^\/+/, '')
      curr = index === 0 && !isReplaceFirst ? curr : nextPath
      pre = pre === '' ? curr : `${pre.replace(/\/+$/, '')}/${nextPath}`
      return pre
    }, '')
  }
 
  /**
   * getUrl 获取请求url完整地址
   * @param {String} api请求地址
   * @param {Object} mixConf 混入后的请求配置
   */
  getUrl(api, mixConf) {
    const { method, body } = mixConf
    if (method.toLocaleLowerCase() === 'get') {
      const str = this.getUrlbody(api, body)
      api = api.includes('?') ? `${api}&${str}` : `${api}?${str}`
    }
    return api
  }
 
  /**
   * getUrlbody 拼接url字符串
   * @param {String} api 接口地址
   * @param {Object|String} body 请求参数
   * @param {Object} conf 请求配置信息
   */
  getUrlbody(api, body) {
    if (typeof body === 'object') {
      body = Object.keys(body).reduce((pre, curr) => {
        const val =
          typeof body[curr] === 'object'
            ? JSON.stringify(body[curr])
            : body[curr]
        pre = pre === '' ? pre : `${pre}&`
        pre = `${pre}${curr}=${val}`
        return pre
      }, '')
    }
    return body
  }
 
  /**
   * getBody 根据headers信息,
   * @param {Object} mixConf 请求配置项
   */
  getBody(mixConf) {
    let { body, headers } = mixConf
    if (typeof headers === 'object') {
      Object.keys(headers).forEach(key => {
        if (key.toLocaleLowerCase() === 'content-type') {
          // json string
          if (
            headers[key].includes('application/json') &&
            typeof body !== 'string'
          ) {
            body = JSON.stringify(body)
          }
 
          // body
          if (headers[key].includes('application/x-www-form-urlencoded')) {
            body = this.getUrlbody(body)
          }
 
          // file
          if (
            headers[key].includes('multipart/form-data') &&
            !(body instanceof FormData)
          ) {
            const formData = new FormData()
            Object.keys(body).forEach(key => {
              formData.append(key, body[key])
            })
          }
        }
      })
    }
    return body
  }
 
  /**
   * 请求统一入口
   * @param {String} api 接口地址
   * @param {Object|String} body 请求参数
   * @param {Object} conf 请求配置信息
   */
  toFetch(api, body = {}, conf = {}) {
    const { url, ...other } = this.mixConf(api, body, conf)
    return new Promise((resolve, reject) => {
      fetch(url, other).then(res => {
        if (res.ok) {
          resolve(res.json())
        }
        reject(new Error(`接口:${url},请求异常!`))
      })
    })
  }
}