Request.js 12 KB

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