http.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import axios from "axios";
  2. class WrappedAxios {
  3. constructor(options = {}) {
  4. this.instance = axios.create(Object.assign({ timeout: 10000 }, options));
  5. }
  6. beforeRequest(onFulfilled, onRejected, options) {
  7. this.instance.interceptors.request.use(onFulfilled, onRejected, options);
  8. return this;
  9. }
  10. afterResponse(onFulfilled, onRejected, options) {
  11. this.instance.interceptors.response.use(onFulfilled, onRejected, options);
  12. return this;
  13. }
  14. get axiosInstance() {
  15. return this.instance;
  16. }
  17. get(url, data, config = {}) {
  18. return this.instance.get(url, Object.assign({ params: data }, config));
  19. }
  20. post(url, data, config = {}) {
  21. return this.instance.post(url, data, config);
  22. }
  23. put(url, data, config = {}) {
  24. return this.instance.put(url, data, config);
  25. }
  26. delete(url, data, config = {}) {
  27. return this.instance.delete(url, Object.assign({ params: data }, config));
  28. }
  29. createCancelObj(config = {}, send) {
  30. const controller = new AbortController();
  31. config.signal = controller.signal;
  32. return {
  33. cancel() {
  34. controller.abort();
  35. },
  36. send,
  37. };
  38. }
  39. createGetWithCancel(url, data, config = {}) {
  40. return this.createCancelObj(config, () => {
  41. return this.get(url, data, config);
  42. });
  43. }
  44. createPostWithCancel(url, data, config = {}) {
  45. return this.createCancelObj(config, () => {
  46. return this.post(url, data, config);
  47. });
  48. }
  49. createPutWithCancel(url, data, config = {}) {
  50. return this.createCancelObj(config, () => {
  51. return this.put(url, data, config);
  52. });
  53. }
  54. createDeleteWithCancel(url, data, config = {}) {
  55. return this.createCancelObj(config, () => {
  56. return this.delete(url, data, config);
  57. });
  58. }
  59. }
  60. const http = new WrappedAxios();
  61. http
  62. .beforeRequest((config) => {
  63. config.headers.token = "123";
  64. return config;
  65. })
  66. .afterResponse((response) => {
  67. return response.data;
  68. }, (error) => {
  69. return Promise.reject(error);
  70. });
  71. http.get("/a", { a: 1 });
  72. const req = http.createGetWithCancel("/a", { a: 1 });
  73. req.send();
  74. setTimeout(() => {
  75. req.cancel();
  76. });
  77. export { WrappedAxios };