mpyw / axios-case-converter

Axios transformer/interceptor that converts snake_case/camelCase
MIT License
160 stars 18 forks source link

Answers for #39 and #40 #43

Closed mpyw closed 3 years ago

mpyw commented 3 years ago

Answers for #39 and #40

I'm sorry that I'm not willing to implement these features now. I'll explain some reasons. See also the following implementation for reference.

export const applyCaseMiddleware: ApplyCaseMiddleware = (axios, options?) => {
  axios.defaults.transformRequest = [
    options?.caseMiddleware?.requestTransformer ||
      createSnakeRequestTransformer(options),
    ...(Array.isArray(axios.defaults.transformRequest)
      ? axios.defaults.transformRequest
      : axios.defaults.transformRequest !== undefined
      ? [axios.defaults.transformRequest]
      : []),
  ];
  axios.defaults.transformResponse = [
    ...(Array.isArray(axios.defaults.transformResponse)
      ? axios.defaults.transformResponse
      : axios.defaults.transformResponse !== undefined
      ? [axios.defaults.transformResponse]
      : []),
    options?.caseMiddleware?.responseTransformer ||
      createCamelResponseTransformer(options),
  ];
  axios.interceptors.request.use(
    options?.caseMiddleware?.requestInterceptor ||
      createSnakeParamsInterceptor(options)
  );
  return axios;
};

Interceptor

According to the Official Documentation, you can manually apply interceptor like this:

axios.interceptors.request.use(
  options?.caseMiddleware?.requestInterceptor ||
    createSnakeParamsInterceptor(options),
  null,
  { runWhen(config) { /* ... */ } }
);

With this feature, it is possible to implement it on the library side. But I'm not willing to do so because it is difficult to achieve the same functionality on Transformer and it also looks unstable.

Transformer

The implementation in Transformer corresponding to the Interceptor checking runWhen() is the following part.

It looks quite difficult to determine the URL in this layer since request config is not given as an argument here.

Conclusion

The current best practice is: