Skip to content

Instantly share code, notes, and snippets.

@felixmosh
Last active February 9, 2022 10:08
Show Gist options
  • Save felixmosh/f38f236b897c3889595c4cfd7188790d to your computer and use it in GitHub Desktop.
Save felixmosh/f38f236b897c3889595c4cfd7188790d to your computer and use it in GitHub Desktop.
Abort axios request on DEV mode
import { devModeInterceptor } from './devModeInterceptor';
class CriticalAPI {
private axios: AxiosInstance;
constructor() {
this.axios = Axios.create({
baseURL: process.env.BASE_URL,
});
this.axios.interceptors.request.use(devModeInterceptor);
}
public chargeCC(ccId: string) {
return this.axios.post(`/charge-cc`, {
ccId,
});
}
}
import { AxiosRequestConfig } from 'axios';
export function devModeInterceptor(config: AxiosRequestConfig) {
if (process.env.NODE_ENV === 'production') {
return config;
}
console.info(
{
method: config.method,
baseUrl: config.baseURL,
url: config.url,
headers: Object.keys(config.headers).reduce((newHeaders, key) => {
if (typeof config.headers[key] === 'string') {
newHeaders[key] = config.headers[key];
}
return newHeaders;
}, {}),
params: config.params,
data: config.data,
},
`Request skipped in ${process.env.NODE_ENV} mode`
);
return { adapter: () => Promise.resolve({ data: {} }) };
}
@felixmosh
Copy link
Author

This gist demonstrate how you can cancel Axios request on none production mode.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment