|
@@ -0,0 +1,77 @@
|
|
|
|
+import axios from "axios";
|
|
|
|
+class WrappedAxios {
|
|
|
|
+ constructor(options = {}) {
|
|
|
|
+ this.instance = axios.create(Object.assign({ timeout: 10000 }, options));
|
|
|
|
+ }
|
|
|
|
+ beforeRequest(onFulfilled, onRejected, options) {
|
|
|
|
+ this.instance.interceptors.request.use(onFulfilled, onRejected, options);
|
|
|
|
+ return this;
|
|
|
|
+ }
|
|
|
|
+ afterResponse(onFulfilled, onRejected, options) {
|
|
|
|
+ this.instance.interceptors.response.use(onFulfilled, onRejected, options);
|
|
|
|
+ return this;
|
|
|
|
+ }
|
|
|
|
+ get axiosInstance() {
|
|
|
|
+ return this.instance;
|
|
|
|
+ }
|
|
|
|
+ get(url, data, config = {}) {
|
|
|
|
+ return this.instance.get(url, Object.assign({ params: data }, config));
|
|
|
|
+ }
|
|
|
|
+ post(url, data, config = {}) {
|
|
|
|
+ return this.instance.post(url, data, config);
|
|
|
|
+ }
|
|
|
|
+ put(url, data, config = {}) {
|
|
|
|
+ return this.instance.put(url, data, config);
|
|
|
|
+ }
|
|
|
|
+ delete(url, data, config = {}) {
|
|
|
|
+ return this.instance.delete(url, Object.assign({ params: data }, config));
|
|
|
|
+ }
|
|
|
|
+ createCancelObj(config = {}, send) {
|
|
|
|
+ const controller = new AbortController();
|
|
|
|
+ config.signal = controller.signal;
|
|
|
|
+ return {
|
|
|
|
+ cancel() {
|
|
|
|
+ controller.abort();
|
|
|
|
+ },
|
|
|
|
+ send,
|
|
|
|
+ };
|
|
|
|
+ }
|
|
|
|
+ createGetWithCancel(url, data, config = {}) {
|
|
|
|
+ return this.createCancelObj(config, () => {
|
|
|
|
+ return this.get(url, data, config);
|
|
|
|
+ });
|
|
|
|
+ }
|
|
|
|
+ createPostWithCancel(url, data, config = {}) {
|
|
|
|
+ return this.createCancelObj(config, () => {
|
|
|
|
+ return this.post(url, data, config);
|
|
|
|
+ });
|
|
|
|
+ }
|
|
|
|
+ createPutWithCancel(url, data, config = {}) {
|
|
|
|
+ return this.createCancelObj(config, () => {
|
|
|
|
+ return this.put(url, data, config);
|
|
|
|
+ });
|
|
|
|
+ }
|
|
|
|
+ createDeleteWithCancel(url, data, config = {}) {
|
|
|
|
+ return this.createCancelObj(config, () => {
|
|
|
|
+ return this.delete(url, data, config);
|
|
|
|
+ });
|
|
|
|
+ }
|
|
|
|
+}
|
|
|
|
+const http = new WrappedAxios();
|
|
|
|
+http
|
|
|
|
+ .beforeRequest((config) => {
|
|
|
|
+ config.headers.token = "123";
|
|
|
|
+ return config;
|
|
|
|
+})
|
|
|
|
+ .afterResponse((response) => {
|
|
|
|
+ return response.data;
|
|
|
|
+}, (error) => {
|
|
|
|
+ return Promise.reject(error);
|
|
|
|
+});
|
|
|
|
+http.get("/a", { a: 1 });
|
|
|
|
+const req = http.createGetWithCancel("/a", { a: 1 });
|
|
|
|
+req.send();
|
|
|
|
+setTimeout(() => {
|
|
|
|
+ req.cancel();
|
|
|
|
+});
|
|
|
|
+export { WrappedAxios };
|