LoginSignup
1
0

axiosのrequest/response Object keyのケース変換を行うライブラリを公開した話

Last updated at Posted at 2023-10-23

はじめに

axiosを利用してAPIを呼び出しているアプリケーションは無数にあると思う。しかし、キーのケース違いで実装にわずらわしさを感じる場面も少なくない。

具体的には、REST APIではsnake_caseだが、JavaScript/TypeScriptではcamelCaseというのはよくあるだろう。

今回はそのケース違いによる煩わしさ(ケース変換の手間)をなくしてくれるライブラリを公開したので、そのライブラリの紹介をしたいと思う。

simple-axios-case-converter

というライブラリを利用することで、ケース変換の手間から解放される。

利用方法は簡単で、以下のようにaxiosをこのライブラリの関数に渡すだけ。

import axios from 'axios';
import axiosCaseConverter from 'simple-axios-case-converter';

axiosCaseConverter(axios);

これで、あとはいつも通りにaxios.get()axios.post()などを使ってAPIを呼び出せばいい。実装時はすべてcamelCaseで実装できる。

// you need not convert request `params` to snake_case
axios.get('https://example.com/api/v1/todos', { params: { onlyComplete: true } });

// you need not convert request `data` to snake_case
axios.post('https://example.com/api/v1/address', {
	countryCode: 'JP',
	postalCode: '123-4567',
	prefecture: 'Tokyo',
	city: 'Shibuya'
});

// you need not convert request `data` to snake_case
axios.patch('https://example.com/api/v1/address/123', { postalCode: '123-4567' });

// you need not convert request `data` to snake_case
axios.delete('https://example.com/api/v1/address/123', { data: { addressId: 123 } });

このライブラリはaxiosのinterceptorを利用しているので、もしケース変換をしないようにしたい場合には、以下のようにejectを利用すればいい。

const { requestInterceptorId, responseInterceptorId } = axiosCaseConverter(axios);
axios.interceptors.request.eject(requestInterceptorId);
axios.interceptors.response.eject(responseInterceptorId);

まとめとして

似たようなライブラリにaxios-case-converterがあるが、そのライブラリをよりシンプルにしたものとして今回、simple-axios-case-converterを公開してみた。

※詳細の違いについてはWhat is different from axios-case-converterを参照ください。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0