Request.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. /**
  2. * Request 2.0.1
  3. * @Class Request
  4. * @description luch-request 2.0.1 http请求插件
  5. * @Author lu-ch
  6. * @Date 2020-05-01
  7. * @Email webwork.s@qq.com
  8. * http://ext.dcloud.net.cn/plugin?id=392
  9. * hbuilderx:2.6.15
  10. */
  11. import buildURL from '../helpers/buildURL'
  12. import buildFullPath from './buildFullPath'
  13. import { isBoolean } from '../utils'
  14. import {ACCESS_TOKEN} from '@/common/util/constants.js'
  15. export default class Request {
  16. config = {
  17. baseUrl: '',
  18. header: {},
  19. method: 'GET',
  20. dataType: 'json',
  21. // #ifndef MP-ALIPAY || APP-PLUS
  22. responseType: 'text',
  23. // #endif
  24. custom: {},
  25. // #ifdef MP-ALIPAY || MP-WEIXIN
  26. timeout: 30000,
  27. // #endif
  28. // #ifdef APP-PLUS
  29. sslVerify: true,
  30. // #endif
  31. // #ifdef H5
  32. withCredentials: false
  33. // #endif
  34. }
  35. /**
  36. * @property {Function} request 请求拦截器
  37. * @property {Function} response 响应拦截器
  38. * @type {{request: Request.interceptor.request, response: Request.interceptor.response}}
  39. */
  40. interceptor = {
  41. /**
  42. * @param {Request~requestCallback} cb - 请求之前拦截,接收一个函数(config, cancel)=> {return config}。第一个参数为全局config,第二个参数为函数,调用则取消本次请求。
  43. */
  44. request: (cb) => {
  45. if (cb) {
  46. this.requestBeforeFun = cb
  47. }
  48. },
  49. /**
  50. * @param {Request~responseCallback} cb 响应拦截器,对响应数据做点什么
  51. * @param {Request~responseErrCallback} ecb 响应拦截器,对响应错误做点什么
  52. */
  53. response: (cb, ecb) => {
  54. if (cb) {
  55. this.requestComFun = cb
  56. }
  57. if (ecb) {
  58. this.requestComFail = ecb
  59. }
  60. }
  61. }
  62. requestBeforeFun = (config) => {
  63. return config
  64. }
  65. requestComFun = (response) => {
  66. return response
  67. }
  68. requestComFail = (response) => {
  69. return response
  70. }
  71. /**
  72. * 自定义验证器,如果返回true 则进入响应拦截器的响应成功函数(resolve),否则进入响应拦截器的响应错误函数(reject)
  73. * @param { Number } statusCode - 请求响应体statusCode(只读)
  74. * @return { Boolean } 如果为true,则 resolve, 否则 reject
  75. */
  76. validateStatus(statusCode) {
  77. return statusCode === 200
  78. }
  79. /**
  80. * @Function
  81. * @param {Request~setConfigCallback} f - 设置全局默认配置
  82. */
  83. setConfig(f) {
  84. this.config = f(this.config)
  85. }
  86. /**
  87. * @Function
  88. * @param {Object} options - 请求配置项
  89. * @prop {String} options.url - 请求路径
  90. * @prop {Object} options.data - 请求参数
  91. * @prop {Object} [options.responseType = config.responseType] [text|arraybuffer] - 响应的数据类型
  92. * @prop {Object} [options.dataType = config.dataType] - 如果设为 json,会尝试对返回的数据做一次 JSON.parse
  93. * @prop {Object} [options.header = config.header] - 请求header
  94. * @prop {Object} [options.method = config.method] - 请求方法
  95. * @returns {Promise<unknown>}
  96. */
  97. async request(options = {}) {
  98. return new Promise((resolve, reject) => {
  99. options.baseUrl = this.config.baseUrl
  100. options.dataType = options.dataType || this.config.dataType
  101. // #ifndef MP-ALIPAY || APP-PLUS
  102. options.responseType = options.responseType || this.config.responseType
  103. // #endif
  104. // #ifdef MP-ALIPAY || MP-WEIXIN
  105. options.timeout = options.timeout || this.config.timeout
  106. // #endif
  107. // #ifdef H5
  108. options.withCredentials = isBoolean(options.withCredentials) ? options.withCredentials : this.config.withCredentials
  109. // #endif
  110. options.url = options.url || ''
  111. options.data = options.data || {}
  112. options.params = options.params || {}
  113. options.header = {...this.config.header, ...(options.header || {})}
  114. options.method = options.method || this.config.method
  115. options.custom = {...this.config.custom,...(options.custom || {})}
  116. // #ifdef APP-PLUS
  117. options.sslVerify = options.sslVerify === undefined ? this.config.sslVerify : options.sslVerify
  118. // #endif
  119. options.getTask = options.getTask || this.config.getTask
  120. let next = true
  121. const cancel = (t = 'handle cancel', config = options) => {
  122. const err = {
  123. errMsg: t,
  124. config: config
  125. }
  126. reject(err)
  127. next = false
  128. }
  129. const handleRe = {...this.requestBeforeFun(options, cancel)}
  130. const _config = {...handleRe}
  131. if (!next) return
  132. const requestTask = uni.request({
  133. url: buildURL(buildFullPath(_config.baseUrl, _config.url), _config.params),
  134. data: _config.data,
  135. header: _config.header,
  136. method: _config.method,
  137. // #ifdef MP-ALIPAY || MP-WEIXIN
  138. timeout: _config.timeout,
  139. // #endif
  140. dataType: _config.dataType,
  141. // #ifndef MP-ALIPAY || APP-PLUS
  142. responseType: _config.responseType,
  143. // #endif
  144. // #ifdef APP-PLUS
  145. sslVerify: _config.sslVerify,
  146. // #endif
  147. // #ifdef H5
  148. withCredentials: _config.withCredentials,
  149. // #endif
  150. complete: (response) => {
  151. response.config = handleRe
  152. if (this.validateStatus(response.statusCode)) { // 成功
  153. response = this.requestComFun(response)
  154. resolve(response)
  155. } else {
  156. response = this.requestComFail(response)
  157. reject(response)
  158. }
  159. }
  160. })
  161. if (handleRe.getTask) {
  162. handleRe.getTask(requestTask, handleRe)
  163. }
  164. })
  165. }
  166. get(url, options = {}) {
  167. return this.request({
  168. url,
  169. method: 'GET',
  170. ...options
  171. })
  172. }
  173. post(url, data, options = {}) {
  174. return this.request({
  175. url,
  176. data,
  177. method: 'POST',
  178. ...options
  179. })
  180. }
  181. // #ifndef MP-ALIPAY
  182. put(url, data, options = {}) {
  183. return this.request({
  184. url,
  185. data,
  186. method: 'PUT',
  187. ...options
  188. })
  189. }
  190. // #endif
  191. // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-BAIDU
  192. delete(url, data, options = {}) {
  193. return this.request({
  194. url,
  195. data,
  196. method: 'DELETE',
  197. ...options
  198. })
  199. }
  200. // #endif
  201. // #ifdef APP-PLUS || H5 || MP-WEIXIN
  202. connect(url, data, options = {}) {
  203. return this.request({
  204. url,
  205. data,
  206. method: 'CONNECT',
  207. ...options
  208. })
  209. }
  210. // #endif
  211. // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-BAIDU
  212. head(url, data, options = {}) {
  213. return this.request({
  214. url,
  215. data,
  216. method: 'HEAD',
  217. ...options
  218. })
  219. }
  220. // #endif
  221. // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-BAIDU
  222. options(url, data, options = {}) {
  223. return this.request({
  224. url,
  225. data,
  226. method: 'OPTIONS',
  227. ...options
  228. })
  229. }
  230. // #endif
  231. // #ifdef APP-PLUS || H5 || MP-WEIXIN
  232. trace(url, data, options = {}) {
  233. return this.request({
  234. url,
  235. data,
  236. method: 'TRACE',
  237. ...options
  238. })
  239. }
  240. // #endif
  241. upload(url, {
  242. // #ifdef APP-PLUS || H5
  243. files,
  244. // #endif
  245. // #ifdef MP-ALIPAY
  246. fileType,
  247. // #endif
  248. filePath,
  249. name,
  250. // #ifdef H5
  251. file,
  252. // #endif
  253. header = {},
  254. formData = {},
  255. custom = {},
  256. params = {},
  257. getTask
  258. }) {
  259. return new Promise((resolve, reject) => {
  260. let next = true
  261. const globalHeader = {...this.config.header}
  262. delete globalHeader['content-type']
  263. delete globalHeader['Content-Type']
  264. const pubConfig = {
  265. baseUrl: this.config.baseUrl,
  266. url,
  267. // #ifdef MP-ALIPAY
  268. fileType,
  269. // #endif
  270. filePath,
  271. method: 'UPLOAD',
  272. name,
  273. header: {...globalHeader, ...header},
  274. formData,
  275. params,
  276. custom: {...this.config.custom, ...custom},
  277. getTask: getTask || this.config.getTask
  278. }
  279. // #ifdef APP-PLUS || H5
  280. if (files) {
  281. pubConfig.files = files
  282. }
  283. // #endif
  284. // #ifdef H5
  285. if (file) {
  286. pubConfig.file = file
  287. }
  288. // #endif
  289. const cancel = (t = 'handle cancel', config = pubConfig) => {
  290. const err = {
  291. errMsg: t,
  292. config: config
  293. }
  294. reject(err)
  295. next = false
  296. }
  297. const handleRe = {...this.requestBeforeFun(pubConfig, cancel)}
  298. const _config = {
  299. url: buildURL(buildFullPath(handleRe.baseUrl, handleRe.url), handleRe.params),
  300. // #ifdef MP-ALIPAY
  301. fileType: handleRe.fileType,
  302. // #endif
  303. filePath: handleRe.filePath,
  304. name: handleRe.name,
  305. header: handleRe.header,
  306. formData: handleRe.formData,
  307. complete: (response) => {
  308. response.config = handleRe
  309. try {
  310. // 对可能字符串不是json 的情况容错
  311. if (typeof response.data === 'string') {
  312. response.data = JSON.parse(response.data)
  313. }
  314. // eslint-disable-next-line no-empty
  315. } catch (e) {
  316. }
  317. if (this.validateStatus(response.statusCode)) { // 成功
  318. response = this.requestComFun(response)
  319. resolve(response)
  320. } else {
  321. response = this.requestComFail(response)
  322. reject(response)
  323. }
  324. }
  325. }
  326. // #ifdef APP-PLUS || H5
  327. if (handleRe.files) {
  328. _config.files = handleRe.files
  329. }
  330. // #endif
  331. // #ifdef H5
  332. if (handleRe.file) {
  333. _config.file = handleRe.file
  334. }
  335. // #endif
  336. if (!next) return
  337. const requestTask = uni.uploadFile(_config)
  338. if (handleRe.getTask) {
  339. handleRe.getTask(requestTask, handleRe)
  340. }
  341. })
  342. }
  343. download(url, options = {}) {
  344. return new Promise((resolve, reject) => {
  345. let next = true
  346. const pubConfig = {
  347. baseUrl: this.config.baseUrl,
  348. url,
  349. method: 'DOWNLOAD',
  350. header: {...this.config.header, ...(options.header || {})},
  351. params: options.params || {},
  352. custom: {...this.config.custom, ...(options.custom || {})},
  353. getTask: options.getTask || this.config.getTask
  354. }
  355. const cancel = (t = 'handle cancel', config = pubConfig) => {
  356. const err = {
  357. errMsg: t,
  358. config: config
  359. }
  360. reject(err)
  361. next = false
  362. }
  363. const handleRe = {...this.requestBeforeFun(pubConfig, cancel)}
  364. if (!next) return
  365. const requestTask = uni.downloadFile({
  366. url: buildURL(buildFullPath(handleRe.baseUrl, handleRe.url), handleRe.params),
  367. header: handleRe.header,
  368. complete: (response) => {
  369. response.config = handleRe
  370. if (this.validateStatus(response.statusCode)) { // 成功
  371. response = this.requestComFun(response)
  372. resolve(response)
  373. } else {
  374. response = this.requestComFail(response)
  375. reject(response)
  376. }
  377. }
  378. })
  379. if (handleRe.getTask) {
  380. handleRe.getTask(requestTask, handleRe)
  381. }
  382. })
  383. }
  384. }
  385. /**
  386. * setConfig回调
  387. * @return {Object} - 返回操作后的config
  388. * @callback Request~setConfigCallback
  389. * @param {Object} config - 全局默认config
  390. */
  391. /**
  392. * 请求拦截器回调
  393. * @return {Object} - 返回操作后的config
  394. * @callback Request~requestCallback
  395. * @param {Object} config - 全局config
  396. * @param {Function} [cancel] - 取消请求钩子,调用会取消本次请求
  397. */
  398. /**
  399. * 响应拦截器回调
  400. * @return {Object} - 返回操作后的response
  401. * @callback Request~responseCallback
  402. * @param {Object} response - 请求结果 response
  403. */
  404. /**
  405. * 响应错误拦截器回调
  406. * @return {Object} - 返回操作后的response
  407. * @callback Request~responseErrCallback
  408. * @param {Object} response - 请求结果 response
  409. */