If you work on a project in which the frontend and backend are developed in different languages, there is a high probability that you will have values with different naming conventions traveling through HTTP requests.
In this short article I will show you a strategy so that you can maintain the naming convention of the values according to the programming language you are using and thus maintain a standardised code style in your applications.
First of all, you need to install axios and a library called humps in your project:
yarn add axios humps @types/humps
That done, you can configure the axios interceptors as follows:
import axios, { AxiosResponse, AxiosRequestConfig } from 'axios';
import { camelizeKeys, decamelizeKeys } from 'humps';
const api = axios.create({ baseURL: 'localhost:3000' });
// Axios middleware to convert all api responses to camelCase
api.interceptors.response.use((response: AxiosResponse) => {
if (
response.data &&
response.headers['content-type'] === 'application/json'
) {
response.data = camelizeKeys(response.data);
}
return response;
});
// Axios middleware to convert all api requests to snake_case
api.interceptors.request.use((config: AxiosRequestConfig) => {
const newConfig = { ...config };
newConfig.url = `api/${config.url}`;
if (newConfig.headers['Content-Type'] === 'multipart/form-data')
return newConfig;
if (config.params) {
newConfig.params = decamelizeKeys(config.params);
}
if (config.data) {
newConfig.data = decamelizeKeys(config.data);
}
return newConfig;
});
export default api;
Note that in the code above, some validations are made to check whether the intercepted call should be converted or not. You can add as many validations as you need.
#axios #programming #react #web #javascript