1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- 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 };
|