mpyw / axios-case-converter

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

preserve case #27

Closed alextrastero closed 4 years ago

alextrastero commented 4 years ago

I switched from camelize to this project because this allowed configuration.

I know issues are not for how tos but maybe you have a quick answer...

How to not change case? BMX is being converted into bmx

mpyw commented 4 years ago

You have two options:

In this case, probably, you should choose caseFunctions.

mpyw commented 4 years ago

For example, if you want to keep two or more adjacent capital letters, you can do:

const options = {
  caseFunctions: {
    camel: (input, options) => {
      return input.replace(/([A-Z]{2,})|(.*)/g, (match, group1, group2) => {
        if (group1) {
          return group1;
        }
        return (group2.charAt(0).toLowerCase() + group2.slice(1)).replace(/[-_](.)/g, (match, group1) => group1.toUpperCase());
      });
    }
  }
};

Tested on Node.js:

> options.caseFunctions.camel('foo_bar_BMX')
'fooBarBMX'
> options.caseFunctions.camel('foo_bar_BMX_testing')
'fooBarBMXTesting'
alextrastero commented 4 years ago

Thank you for your time, my final code looks like so:

const axiosClient = applyConverters(axios.create(), {
  // does not convert `en-GB` nor `great britain`
  preservedKeys: input => input.includes('-') || input.includes(' '),
  caseFunctions: {
    // overrides change-case to only replace words like `one_two`
    camel: (input) => {
      return input.replace(/([_][a-z])/ig, ($1) => {
        return $1.toUpperCase().replace('_', '');
      });
    }
  }
});