• Stars
    star
    157
  • Rank 237,713 (Top 5 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 7 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Axios transformer/interceptor that converts snake_case/camelCase

axios-case-converter

npm version Build Status Coverage Status

Axios transformer/interceptor that converts snake_case/camelCase

  • Converts outgoing data params object keys into snake_case
  • Converts incoming data object keys into camelCase
  • Converts outgoing headers object keys into Header-Case
  • Converts incoming headers object keys into camelCase

Installing

NPM

npm install axios-case-converter

CDN

<script src="https://unpkg.com/axios-case-converter@latest/dist/axios-case-converter.min.js"></script>

It is strongly recommended that you replace latest with a fixed version.

Usage

You can fully use camelCase in your JavaScript codes.

import applyCaseMiddleware from 'axios-case-converter';
import axios from 'axios';

(async () => {
  const client = applyCaseMiddleware(axios.create());
  const { data } = await client.post(
    'https://example.com/api/endpoint',
    {
      targetId: 1
    },
    {
      params: { userId: 1 },
      headers: { userAgent: 'Mozilla' }
    }
  );

  console.log(data.actionResult.users[0].screenName);
})();

Options

const client = applyCaseMiddleware(axios.create(), options);

preservedKeys: string[] | Function

Disable transformation when the string matched or satisfied the condition.

const options = {
  preservedKeys: ['preserve_this_key_1', 'preserve_this_key_2']
};
const options = {
  preservedKeys: (input) => {
    return ['preserve_this_key_1', 'preserve_this_key_2'].includes(input);
  }
};

ignoreHeaders: boolean

Disable HTTP headers transformation.

const options = {
  ignoreHeaders: true
};

ignoreParams: boolean

Disable HTTP URL parameters transformation.

const options = {
  ignoreParams: true
};

caseFunctions: { snake?: Function, camel?: Function, header?: Function }

Override built-in change-case functions.

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

caseOptions: { stripRegexp?: RegExp }

By default, { stripRegexp: /[^A-Z0-9[\]]+/gi } is used as default change-case function options. This preserves [] chars in object keys. If you wish keeping original change-case behavior, override the options.

const options = {
  caseOptions: {
    stripRegexp: /[^A-Z0-9]+/gi
  }
};

caseMiddleware: { requestTransformer?: Function, responseTransformer?: Function, requestInterceptor?: Function }

Totally override axios-case-converter behaviors.

const options = {
  caseMiddleware: {
    requestInterceptor: (config) => {
      // Disable query string transformation
      return config;
    }
  }
};
Check the tests for more info

Attention

Object compatibility

If you run on Internet Explorer, you need polyfill for Object.prorotypte.entries().

FormData compatibility

If you use FormData on Internet Explorer, you need polyfill of FormData.prototype.entries().

If you use FormData on React Native, please ignore the following warnings after confirming that polyfill is impossible.

// RN >= 0.52
import { YellowBox } from 'react-native';
YellowBox.ignoreWarnings([
  'Be careful that FormData cannot be transformed on React Native.'
]);

// RN < 0.52
console.ignoredYellowBox = [
  'Be careful that FormData cannot be transformed on React Native.'
];

Symbol compatibility

If you use React Native for Android development, you should use Symbol polyfill from core-js to avoid bugs with iterators:

  1. Create polyfill.js in root directory with code:
global.Symbol = require('core-js/es6/symbol');
require('core-js/fn/symbol/iterator');
  1. Include polyfill.js in entry point of your app (e.g. app.js):
import { Platform } from 'react-native';

// ...

if (Platform.OS === 'android') {
  require('./polyfill.js');
}

cf. undefined is not a function(evaluating '_iterator[typeof Symbol === "function"?Symbol.iterator:"@@iterator"]()') ยท Issue #15902 ยท facebook/react-native

More Repositories

1

co

Asynchronous cURL executor simply based on resource and Generator.
PHP
136
star
2

cowitter

Asynchronous Twitter client compatible with mpyw/co Generator-based flows.
PHP
116
star
3

php-hyper-builtin-server

Reverse proxy for PHP built-in server which supports multiprocessing and TLS/SSL encryption
PHP
106
star
4

eloquent-has-by-non-dependent-subquery

Convert has() and whereHas() constraints to non-dependent subqueries.
PHP
82
star
5

laravel-cached-database-stickiness

Guarantee database stickiness over the same user's consecutive requests
PHP
75
star
6

comphar

Pack all composer dependencies into a single phar file.
PHP
72
star
7

hub-purge

Clear GitHub image caches on README
Shell
35
star
8

FILTER_VALIDATE_EMAIL.js

TypeScript/JavaScript Email validation compatible with PHP's filter_var($value, FILTER_VALIDATE_EMAIL)
TypeScript
26
star
9

eloquent-has-by-join

Convert has() and whereHas() constraints to join() ones for single-result relations.
PHP
24
star
10

EasyCrypt

A class that provides simple interface for decryptable encryption.
PHP
23
star
11

laravel-local-class-scope

A tiny macro that reuse a global scope class as a local scope
PHP
23
star
12

aws-lambda-billing-slack-notification

Node.js 14 ไปฅ้™ๅ‘ใ‘ใฎ AWS ๅฝ“ๆœˆๅˆฉ็”จๆ–™้‡‘ Slack ้€š็Ÿฅใ‚นใ‚ฏใƒชใƒ—ใƒˆ
TypeScript
22
star
13

null-auth

Null Guard for Laravel. Designed for Middleware-based authentication and testing.
PHP
19
star
14

laravel-database-advisory-lock

Advisory Locking Features for Postgres/MySQL/MariaDB on Laravel
PHP
18
star
15

cloudwatch-front-logger

Save your browser console logs to AWS CloudWatch (Inspired by agea/console-cloud-watch)
TypeScript
17
star
16

phpunit-patch-serializable-comparison

Fixes assertSame()/assertEquals() serialization errors running in separate processes.
PHP
14
star
17

laravel-retry-on-duplicate-key

Automatically retry non-atomic upsert operation when unique key constraints are violated.
PHP
13
star
18

compoships-eager-limit

topclaudy/compoships + staudenmeir/eloquent-eager-limit
PHP
12
star
19

scoped-auth

Apply specific scope for user authentication.
PHP
10
star
20

laravel-mysql-system-variable-manager

A tiny extension of MySqlConnection that manages session system variables
PHP
9
star
21

twhelp

Twitter OAuth CLI Helper distributed by Golang cross-compilation.
Go
8
star
22

uuid-ulid-converter

UUID <=> ULID bidirectional converter
PHP
7
star
23

laravel-packages

Library packages list for Laravel
7
star
24

sqlc-restruct

Post-processor for kyleconroy/sqlc
Go
7
star
25

sharable-value-objects

Share value objects that contain the same primitive value as a singleton
PHP
5
star
26

sql-http-proxy

Go
5
star
27

exceper

Provides temporary error handler automatically using set_error_handler() and restore_error_handler().
PHP
5
star
28

laravel-database-mock

[Experimental] Database Mocking Library which mocks PDO underlying Laravel Connection classes
PHP
5
star
29

my-bookmarklet-collection

5
star
30

BaseUTF8

BaseXX encoder/decoder which support any valid UTF-8 sequences.
PHP
4
star
31

privator

Utils for testing private methods and properties on PHP 7.0+
PHP
3
star
32

noerr

Safe property reference chaining without errors
JavaScript
3
star
33

zenn

Zenn ใฎ่จ˜ไบ‹ไฟ็ฎกๅ ดๆ‰€
3
star
34

docker-clean

Remove all dangling images, volumes, networks and randomly named containers
Shell
2
star
35

mockery-pdo

[Experimental] BDD-style PDO Mocking Library for Mockery
PHP
2
star
36

streamable-console

Call interactive artisan command using arbitrary stream instead of STDIN.
PHP
2
star
37

laravel-pdo-emulation-control

Temporarily enable/disable PDO prepared statement emulation
PHP
2
star
38

mpyw

@mpyw's profile
2
star
39

most-similar

Search most similar word from stdin.
C
1
star
40

unique-violation-detector

Detect primary/unique key or constraint violation errors from PDOException.
PHP
1
star
41

amazon-vod-preset-convert-docker

Docker for https://github.com/aws-samples/amazon-vod-preset-convert
Dockerfile
1
star
42

laravel-unique-violation-detector

Detect primary/unique key or constraint violation errors from PDOException.
PHP
1
star
43

oh-my-zsh-lukerandall-extended

oh-my-zsh lukerandall theme which supports extended features
Shell
1
star
44

suve

Interact with AWS Secrets Manager and Parameter Store
Go
1
star
45

laravel-file-errors

A tiny extension that reports validation error details about uploaded files
PHP
1
star
46

FILTER_VALIDATE_EMAIL.html

HTML Pattern Attribute Validation compatible with PHP's filter_var() and mpyw/FILTER_VALIDATE_EMAIL.js
1
star