http.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. abort() {
  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. export { WrappedAxios };