axios.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /**
  2. * Copyright © 2020 suxinghua. All rights Reserved.
  3. */
  4. const axios = (function () {
  5. class Axios {
  6. constructor() {
  7. this.defaults = {
  8. baseUrl: "",
  9. };
  10. this.interceptors = {
  11. request: new InterceptorManager(),
  12. response: new InterceptorManager(),
  13. };
  14. }
  15. wxRequest(c) {
  16. return new Promise((resolve, reject) => {
  17. c = this.interceptors.request.func(c);
  18. c.url = c.url.startsWith("http") ? c.url : c.baseUrl + c.url;
  19. c.success = (res) => {
  20. resolve(this.interceptors.response.func(res));
  21. };
  22. c.fail = (res) => {
  23. reject(this.interceptors.response.func(res));
  24. };
  25. wx.request(c);
  26. });
  27. }
  28. }
  29. Array.prototype.forEach.call(
  30. ["options", "get", "head", "post", "put", "delete", "trace", "connect"],
  31. function (m) {
  32. Axios.prototype[m] = function (url, data, config) {
  33. return this.wxRequest(
  34. merge(
  35. this.defaults,
  36. {
  37. url: url,
  38. method: m,
  39. data: data,
  40. },
  41. config || {}
  42. )
  43. );
  44. };
  45. }
  46. );
  47. class InterceptorManager {
  48. constructor() {
  49. this.func = function (data) {
  50. return data;
  51. };
  52. }
  53. use(fn) {
  54. this.func = fn;
  55. }
  56. }
  57. function merge(axiosDefaultConfig, data, config) {
  58. let cloneAxios = deepClone(axiosDefaultConfig);
  59. let cloneData = deepClone(data);
  60. let cloneConfig = deepClone(config);
  61. return Object.assign(cloneAxios, cloneData, cloneConfig);
  62. }
  63. // 深拷贝
  64. function deepClone(obj) {
  65. let _obj = JSON.stringify(obj),
  66. objClone = JSON.parse(_obj);
  67. return objClone;
  68. }
  69. return new Axios();
  70. })();
  71. export default axios;