DEV Community

Cover image for Configuring a camelCase to snake_case parser with Axios
Giovanni Antonaccio
Giovanni Antonaccio

Posted on • Originally published at giovanniantonaccio.hashnode.dev

Configuring a camelCase to snake_case parser with Axios

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 namin 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 standardized code style in your applications.

Configuring the parser on the Frontend

First of all, you need to install axios and a library called humps in your project:

yarn add axios humps @types/humps
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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.

With the little code above, you have a parser that manages to maintain the style pattern in the frontend and backend of your applications.

It is also worth mentioning that humps also has functions to convert PascalCase values 😎.

I hope this small tutorial can help you with your projects! Thanks for reading!


If I helped you with this post, consider to buy me a coffee on Ko-Fi πŸ™‚

ko-fi

Top comments (0)