├── test ├── test_helper.exs ├── support │ └── structs.ex ├── casex │ ├── camel_case_encoder_test.exs │ └── camel_case_decoder_plug_test.exs └── casex_test.exs ├── .formatter.exs ├── .gitignore ├── lib ├── casex │ ├── camel_case_decoder_plug.ex │ ├── camel_case_encoder.ex │ └── serializable.ex └── casex.ex ├── README.md ├── .github └── workflows │ └── ci.yml ├── mix.exs ├── mix.lock └── LICENSE /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | -------------------------------------------------------------------------------- /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | casex-*.tar 24 | 25 | -------------------------------------------------------------------------------- /test/support/structs.ex: -------------------------------------------------------------------------------- 1 | defmodule Casex.MySerializableStruct do 2 | defstruct [:cool_key] 3 | 4 | defimpl Casex.Serializable do 5 | def serialize(data), do: Map.take(data, [:cool_key]) 6 | end 7 | end 8 | 9 | defmodule Casex.MyStruct do 10 | defstruct [:cool_key] 11 | end 12 | 13 | defmodule Casex.MyStructDerived do 14 | @derive Casex.Serializable 15 | 16 | defstruct [:cool_key, :another_key] 17 | end 18 | 19 | defmodule Casex.MyStructDerivedWithOnly do 20 | @derive {Casex.Serializable, only: [:cool_key]} 21 | 22 | defstruct [:cool_key, :another_key] 23 | end 24 | 25 | defmodule Casex.MyStructDerivedWithExcept do 26 | @derive {Casex.Serializable, except: [:cool_key]} 27 | 28 | defstruct [:cool_key, :another_key] 29 | end 30 | -------------------------------------------------------------------------------- /lib/casex/camel_case_decoder_plug.ex: -------------------------------------------------------------------------------- 1 | if Code.ensure_loaded?(Plug) do 2 | defmodule Casex.CamelCaseDecoderPlug do 3 | @moduledoc """ 4 | Converts all plug params to snake case. 5 | 6 | ## Usage 7 | 8 | Add `Casex.CamelCaseDecoderPlug` to your api pipeline: 9 | 10 | ```elixir 11 | # router.ex 12 | pipeline :api do 13 | plug :accepts, ["json"] 14 | plug Casex.CamelCaseDecoderPlug 15 | end 16 | ``` 17 | 18 | Now, all request bodies and params will be converted to snake case. 19 | """ 20 | @behaviour Plug 21 | 22 | @impl Plug 23 | def init(opts), do: opts 24 | 25 | @impl Plug 26 | def call(conn, _opts) do 27 | %{conn | params: Casex.to_snake_case(conn.params)} 28 | end 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /lib/casex/camel_case_encoder.ex: -------------------------------------------------------------------------------- 1 | defmodule Casex.CamelCaseEncoder do 2 | @moduledoc """ 3 | Format encoder for phoenix. Converts all the keys of the json data to camel case. 4 | 5 | ## Usage 6 | 7 | Add `Casex.CamelCaseEncoder` as json format encoder for phoenix: 8 | 9 | ``` 10 | # config.exs 11 | config :phoenix, :format_encoders, json: Casex.CamelCaseEncoder 12 | ``` 13 | 14 | Now all outcoming json response bodies will be converted to camel case. 15 | 16 | ## Structs 17 | 18 | If you want to control how the keys will be serilized before being encoded by `Jason`, 19 | you can provide a implementation for the `Casex.Serializable` protocol, by default it 20 | will return the structs as they come, without any transformation. 21 | 22 | """ 23 | 24 | @spec encode_to_iodata!(data :: term()) :: iodata() | no_return() 25 | def encode_to_iodata!(data) do 26 | data 27 | |> Casex.to_camel_case() 28 | |> Jason.encode_to_iodata!() 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /test/casex/camel_case_encoder_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Casex.CamelCaseEncoderTest do 2 | use ExUnit.Case, async: true 3 | 4 | alias Casex.CamelCaseEncoder 5 | 6 | describe "encode_to_iodata!/1" do 7 | test "transforms payload to camel case" do 8 | data = %{ 9 | user: %{ 10 | first_name: "James", 11 | last_name: "Kirk", 12 | crew: [ 13 | %{name: "Spock", serial_number: "S 179-276 SP"}, 14 | %{name: "Scotty", serial_number: "SE 19754 T"} 15 | ] 16 | } 17 | } 18 | 19 | expected_data = %{ 20 | "user" => %{ 21 | "firstName" => "James", 22 | "lastName" => "Kirk", 23 | "crew" => [ 24 | %{"name" => "Spock", "serialNumber" => "S 179-276 SP"}, 25 | %{"name" => "Scotty", "serialNumber" => "SE 19754 T"} 26 | ] 27 | } 28 | } 29 | 30 | result = CamelCaseEncoder.encode_to_iodata!(data) 31 | 32 | assert Jason.decode!(result) == expected_data 33 | end 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Casex 2 | 3 | ![CI](https://github.com/Finbits/casex/workflows/CI/badge.svg?branch=master) 4 | 5 | Simple case conversion for web applications. 6 | Easily decodes `camelCase` body payloads to `snake_case` and 7 | response payloads from `camelCase` to `snake_case`. 8 | Useful to maintain to expose your API in `camelCase` but keep internally the elixir naming conventions. 9 | 10 | It leverages [recase](https://github.com/sobolevn/recase) to provide case conversions 11 | [without relying on the `Macro` module](https://github.com/sobolevn/recase#why) and 12 | easily integrates with [plug](https://hex.pm/packages/plug)-based applications. 13 | 14 | ## Installation 15 | 16 | The package can be installed 17 | by adding `casex` to your list of dependencies in `mix.exs`: 18 | 19 | ```elixir 20 | def deps do 21 | [ 22 | {:casex, "~> 0.4.2"} 23 | ] 24 | end 25 | ``` 26 | 27 | ## Usage 28 | 29 | The complete docs can be found at [https://hexdocs.pm/casex](https://hexdocs.pm/casex). 30 | 31 | ## License 32 | 33 | Copyright 2020 Finbits. 34 | 35 | Casex source code is released under Apache 2 License. 36 | 37 | Check [LICENSE](LICENSE) file for more information. 38 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [pull_request, push] 3 | jobs: 4 | mix_test: 5 | name: mix test (Elixir ${{ matrix.elixir }} OTP ${{ matrix.otp }}) 6 | strategy: 7 | matrix: 8 | elixir: ["1.7.4", "1.8.2", "1.9.4", "1.10.2"] 9 | include: 10 | - elixir: "1.10.2" 11 | otp: "22.3" 12 | - elixir: "1.9.4" 13 | otp: "22.3" 14 | - elixir: "1.8.2" 15 | otp: "21.3.8.14" 16 | - elixir: "1.7.4" 17 | otp: "20.3.8.26" 18 | runs-on: ubuntu-latest 19 | steps: 20 | - uses: actions/checkout@v2 21 | - uses: erlef/setup-beam@v1 22 | with: 23 | otp-version: ${{ matrix.otp }} 24 | elixir-version: ${{ matrix.elixir }} 25 | - name: Install Dependencies 26 | run: mix deps.get 27 | - name: Run Tests 28 | run: mix test 29 | mix_format: 30 | name: mix format (Elixir 1.9.4 OTP 22.3) 31 | runs-on: ubuntu-latest 32 | steps: 33 | - uses: actions/checkout@v2 34 | - uses: erlef/setup-beam@v1 35 | with: 36 | otp-version: "22.3" 37 | elixir-version: "1.9.4" 38 | - name: Install Dependencies 39 | run: mix deps.get 40 | - name: Run Formatter 41 | run: mix format --check-formatted 42 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule Casex.MixProject do 2 | use Mix.Project 3 | 4 | def project do 5 | [ 6 | app: :casex, 7 | version: "0.4.2", 8 | elixir: "~> 1.7", 9 | start_permanent: Mix.env() == :prod, 10 | deps: deps(), 11 | elixirc_paths: elixirc_paths(Mix.env()), 12 | description: "Simple case conversion for web applications", 13 | package: package(), 14 | name: "Casex", 15 | docs: docs() 16 | ] 17 | end 18 | 19 | # Run "mix help compile.app" to learn about applications. 20 | def application do 21 | [ 22 | extra_applications: [:logger] 23 | ] 24 | end 25 | 26 | defp elixirc_paths(:test), do: ["lib", "test/support"] 27 | defp elixirc_paths(_), do: ["lib"] 28 | 29 | # Run "mix help deps" to learn about dependencies. 30 | defp deps do 31 | [ 32 | {:ex_doc, "~> 0.21", only: :dev, runtime: false}, 33 | {:recase, "~> 0.6"}, 34 | {:jason, "~> 1.2"}, 35 | {:plug, "~> 1.10", optional: true} 36 | ] 37 | end 38 | 39 | defp package do 40 | [ 41 | licenses: ["Apache 2.0"], 42 | links: %{"GitHub" => "https://github.com/Finbits/casex"} 43 | ] 44 | end 45 | 46 | defp docs do 47 | [ 48 | main: "Casex", 49 | source_url: "https://github.com/Finbits/casex" 50 | ] 51 | end 52 | end 53 | -------------------------------------------------------------------------------- /test/casex/camel_case_decoder_plug_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Casex.CamelCaseDecoderPlugTest do 2 | use ExUnit.Case, async: true 3 | use Plug.Test 4 | 5 | alias Casex.CamelCaseDecoderPlug 6 | 7 | describe "call/2" do 8 | test "decodes params" do 9 | opts = CamelCaseDecoderPlug.init([]) 10 | 11 | body = %{ 12 | "user" => %{ 13 | "firstName" => "Han", 14 | "lastName" => "Solo", 15 | "alliesInCombat" => [ 16 | %{"name" => "Luke", "weaponOfChoice" => "lightsaber"}, 17 | %{"name" => "Chewie", "weaponOfChoice" => "bowcaster"}, 18 | %{"name" => "Leia", "weaponOfChoice" => "blaster"} 19 | ] 20 | } 21 | } 22 | 23 | conn = conn(:get, "/hello", body) 24 | 25 | conn = CamelCaseDecoderPlug.call(conn, opts) 26 | 27 | assert conn.params == %{ 28 | "user" => %{ 29 | "allies_in_combat" => [ 30 | %{"name" => "Luke", "weapon_of_choice" => "lightsaber"}, 31 | %{"name" => "Chewie", "weapon_of_choice" => "bowcaster"}, 32 | %{"name" => "Leia", "weapon_of_choice" => "blaster"} 33 | ], 34 | "first_name" => "Han", 35 | "last_name" => "Solo" 36 | } 37 | } 38 | end 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /test/casex_test.exs: -------------------------------------------------------------------------------- 1 | defmodule CasexTest do 2 | use ExUnit.Case, async: true 3 | 4 | alias Casex.{ 5 | MyStruct, 6 | MyStructDerived, 7 | MyStructDerivedWithOnly, 8 | MyStructDerivedWithExcept, 9 | MySerializableStruct 10 | } 11 | 12 | doctest Casex 13 | 14 | test "README install version check" do 15 | app = :casex 16 | 17 | app_version = "#{Application.spec(app, :vsn)}" 18 | readme = File.read!("README.md") 19 | [_, readme_versions] = Regex.run(~r/{:#{app}, "(.+)"}/, readme) 20 | 21 | assert Version.match?(app_version, readme_versions) 22 | end 23 | 24 | describe "to_camel_case/1" do 25 | test "struct" do 26 | my_struct = %MyStruct{cool_key: "value"} 27 | 28 | assert Casex.to_camel_case(my_struct) == my_struct 29 | end 30 | 31 | test "seriazable struct" do 32 | my_struct = %MySerializableStruct{cool_key: "value"} 33 | 34 | assert Casex.to_camel_case(my_struct) == %{"coolKey" => "value"} 35 | end 36 | 37 | test "derived struct" do 38 | my_struct = %MyStructDerived{cool_key: "value", another_key: "another"} 39 | 40 | assert Casex.to_camel_case(my_struct) == %{"coolKey" => "value", "anotherKey" => "another"} 41 | end 42 | 43 | test "derived struct with only" do 44 | my_struct = %MyStructDerivedWithOnly{cool_key: "value", another_key: "another"} 45 | 46 | assert Casex.to_camel_case(my_struct) == %{"coolKey" => "value"} 47 | end 48 | 49 | test "derived struct with except" do 50 | my_struct = %MyStructDerivedWithExcept{cool_key: "value", another_key: "another"} 51 | 52 | assert Casex.to_camel_case(my_struct) == %{"anotherKey" => "another"} 53 | end 54 | end 55 | 56 | describe "to_snake_case/1" do 57 | test "struct" do 58 | my_struct = %MyStruct{cool_key: "value"} 59 | 60 | assert Casex.to_snake_case(my_struct) == my_struct 61 | end 62 | end 63 | end 64 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "earmark": {:hex, :earmark, "1.4.4", "4821b8d05cda507189d51f2caeef370cf1e18ca5d7dfb7d31e9cafe6688106a4", [:mix], [], "hexpm", "1f93aba7340574847c0f609da787f0d79efcab51b044bb6e242cae5aca9d264d"}, 3 | "ex_doc": {:hex, :ex_doc, "0.21.3", "857ec876b35a587c5d9148a2512e952e24c24345552259464b98bfbb883c7b42", [:mix], [{:earmark, "~> 1.4", [hex: :earmark, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.14", [hex: :makeup_elixir, repo: "hexpm", optional: false]}], "hexpm", "0db1ee8d1547ab4877c5b5dffc6604ef9454e189928d5ba8967d4a58a801f161"}, 4 | "jason": {:hex, :jason, "1.2.0", "10043418c42d2493d0ee212d3fddd25d7ffe484380afad769a0a38795938e448", [:mix], [{:decimal, "~> 1.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "116747dbe057794c3a3e4e143b7c8390b29f634e16c78a7f59ba75bfa6852e7f"}, 5 | "makeup": {:hex, :makeup, "1.0.1", "82f332e461dc6c79dbd82fbe2a9c10d48ed07146f0a478286e590c83c52010b5", [:mix], [{:nimble_parsec, "~> 0.5.0", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "49736fe5b66a08d8575bf5321d716bac5da20c8e6b97714fec2bcd6febcfa1f8"}, 6 | "makeup_elixir": {:hex, :makeup_elixir, "0.14.0", "cf8b7c66ad1cff4c14679698d532f0b5d45a3968ffbcbfd590339cb57742f1ae", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "d4b316c7222a85bbaa2fd7c6e90e37e953257ad196dc229505137c5e505e9eff"}, 7 | "mime": {:hex, :mime, "1.3.1", "30ce04ab3175b6ad0bdce0035cba77bba68b813d523d1aac73d9781b4d193cf8", [:mix], [], "hexpm", "6cbe761d6a0ca5a31a0931bf4c63204bceb64538e664a8ecf784a9a6f3b875f1"}, 8 | "nimble_parsec": {:hex, :nimble_parsec, "0.5.3", "def21c10a9ed70ce22754fdeea0810dafd53c2db3219a0cd54cf5526377af1c6", [:mix], [], "hexpm", "589b5af56f4afca65217a1f3eb3fee7e79b09c40c742fddc1c312b3ac0b3399f"}, 9 | "plug": {:hex, :plug, "1.10.0", "6508295cbeb4c654860845fb95260737e4a8838d34d115ad76cd487584e2fc4d", [:mix], [{:mime, "~> 1.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4", [hex: :telemetry, repo: "hexpm", optional: true]}], "hexpm", "422a9727e667be1bf5ab1de03be6fa0ad67b775b2d84ed908f3264415ef29d4a"}, 10 | "plug_crypto": {:hex, :plug_crypto, "1.1.2", "bdd187572cc26dbd95b87136290425f2b580a116d3fb1f564216918c9730d227", [:mix], [], "hexpm", "6b8b608f895b6ffcfad49c37c7883e8df98ae19c6a28113b02aa1e9c5b22d6b5"}, 11 | "recase": {:hex, :recase, "0.6.0", "1dd2dd2f4e06603b74977630e739f08b7fedbb9420cc14de353666c2fc8b99f4", [:mix], [], "hexpm", "8712e318420a228eb2e6366ada230148ed3a4316a798319edd5512f64d78c990"}, 12 | } 13 | -------------------------------------------------------------------------------- /lib/casex/serializable.ex: -------------------------------------------------------------------------------- 1 | defprotocol Casex.Serializable do 2 | @moduledoc """ 3 | Protocol controlling how a value is serialized. It is useful to handle custom 4 | structs of your app, without that the `Casex` will be skipped and passed directly to Jason. 5 | 6 | ## Deriving 7 | 8 | The protocol allows leveraging the Elixir's `@derive` feature 9 | to simplify protocol implementation in trivial cases. Accepted 10 | options are: 11 | 12 | * `:only` - encodes only values of specified keys. 13 | * `:except` - encodes all struct fields except specified keys. 14 | 15 | By default all keys except the `:__struct__` key are serialized. 16 | 17 | It also returns a compile time dict of the camelized keys in order 18 | to increase the speed of the case conversion. 19 | 20 | ## Example 21 | 22 | Let's assume a presence of the following struct: 23 | 24 | defmodule Test do 25 | defstruct [:foo, :bar, :baz] 26 | end 27 | 28 | If we were to call `@derive Casex.Serializable` just before `defstruct`, 29 | an implementation similar to the following implementation would be generated: 30 | 31 | defimpl Casex.Serializable, for: Test do 32 | def serialize(data) do 33 | {Map.take(data, [:foo, :bar, :baz]), %{foo: "foo", bar: "bar", baz: "baz"}} 34 | end 35 | end 36 | 37 | If we called `@derive {Casex.Serializable, only: [:foo]}`, an implementation 38 | similar to the following implementation would be generated: 39 | 40 | defimpl Casex.Serializable, for: Test do 41 | def serialize(data) do 42 | {Map.take(data, [:foo]), %{foo: "foo"}} 43 | end 44 | end 45 | 46 | If we called `@derive {Casex.Serializable, except: [:foo]}`, an implementation 47 | similar to the following implementation would be generated: 48 | 49 | defimpl Casex.Serializable, for: Test do 50 | def serialize(data) do 51 | {Map.take(data, [:bar, :baz]), %{bar: "bar", baz: "baz"}} 52 | end 53 | end 54 | 55 | """ 56 | 57 | @fallback_to_any true 58 | @spec serialize(data :: any()) :: any() | {any(), camelized_dict :: map()} 59 | def serialize(data) 60 | end 61 | 62 | defimpl Casex.Serializable, for: Any do 63 | defmacro __deriving__(module, struct, options) do 64 | fields = fields_to_encode(struct, options) 65 | 66 | camelized_dict = 67 | fields 68 | |> Enum.map(fn field -> {field, field |> to_string() |> Recase.to_camel()} end) 69 | |> Map.new() 70 | 71 | quote do 72 | defimpl Casex.Serializable, for: unquote(module) do 73 | def serialize(data) do 74 | {Map.take(data, unquote(fields)), unquote(Macro.escape(camelized_dict))} 75 | end 76 | end 77 | end 78 | end 79 | 80 | def serialize(data), do: data 81 | 82 | defp fields_to_encode(struct, opts) do 83 | cond do 84 | only = Keyword.get(opts, :only) -> 85 | only 86 | 87 | except = Keyword.get(opts, :except) -> 88 | Map.keys(struct) -- [:__struct__ | except] 89 | 90 | true -> 91 | Map.keys(struct) -- [:__struct__] 92 | end 93 | end 94 | end 95 | -------------------------------------------------------------------------------- /lib/casex.ex: -------------------------------------------------------------------------------- 1 | defmodule Casex do 2 | @moduledoc """ 3 | Simple case conversion for web applications. 4 | Easily decodes `camelCase` body payloads to `snake_case` and 5 | response payloads from `camelCase` to `snake_case`. 6 | Useful to maintain to expose your API in `camelCase` but keep internally the elixir naming conventions. 7 | 8 | It leverages [recase](https://github.com/sobolevn/recase) to provide case conversions 9 | without relying on the `Macro` module and 10 | easily integrates with [plug](https://hex.pm/packages/plug)-based applications. 11 | 12 | ## Phoenix Integration 13 | 14 | 1. Add `Casex.CamelCaseDecoderPlug` to your api pipeline: 15 | 16 | ```elixir 17 | # router.ex 18 | pipeline :api do 19 | plug :accepts, ["json"] 20 | plug Casex.CamelCaseDecoderPlug 21 | end 22 | ``` 23 | Now, all request bodies and params will be converted to snake case. 24 | 25 | 26 | 2. Add `Casex.CamelCaseEncoder` as json format encoder for phoenix: 27 | 28 | ```elixir 29 | # config.exs 30 | config :phoenix, :format_encoders, json: Casex.CamelCaseEncoder 31 | ``` 32 | 33 | Now all outcoming json response bodies will be converted to camel case. 34 | """ 35 | 36 | alias Casex.Serializable 37 | 38 | @doc """ 39 | Converts all keys of a map to snake case. 40 | If the map is a struct with no `Enumerable` implementation the value is returned without convertion. 41 | 42 | ## Examples 43 | 44 | iex> data = %{ 45 | ...> "user" => %{ 46 | ...> "firstName" => "James", 47 | ...> "lastName" => "Kirk", 48 | ...> "crew" => [ 49 | ...> %{"name" => "Spock", "serialNumber" => "S 179-276 SP"}, 50 | ...> %{"name" => "Scotty", "serialNumber" => "SE 19754 T"} 51 | ...> ] 52 | ...> } 53 | ...> } 54 | iex> Casex.to_snake_case(data) 55 | %{ 56 | "user" => %{ 57 | "first_name" => "James", 58 | "last_name" => "Kirk", 59 | "crew" => [ 60 | %{"name" => "Spock", "serial_number" => "S 179-276 SP"}, 61 | %{"name" => "Scotty", "serial_number" => "SE 19754 T"} 62 | ] 63 | } 64 | } 65 | 66 | """ 67 | @spec to_snake_case(data :: term()) :: term() 68 | def to_snake_case(data) when is_map(data) do 69 | data 70 | |> Enum.map(fn {key, value} -> {snake_case(key), to_snake_case(value)} end) 71 | |> Enum.into(%{}) 72 | rescue 73 | Protocol.UndefinedError -> data 74 | end 75 | 76 | def to_snake_case(data) when is_list(data) do 77 | Enum.map(data, &to_snake_case/1) 78 | end 79 | 80 | def to_snake_case(data), do: data 81 | 82 | defp snake_case(value) when is_atom(value) do 83 | value 84 | |> to_string() 85 | |> snake_case() 86 | end 87 | 88 | defp snake_case(value) when is_binary(value) do 89 | Recase.to_snake(value) 90 | end 91 | 92 | @doc """ 93 | Converts all keys of a map to camel case. 94 | If the map is a struct with no `Enumerable` implementation the value is returned without convertion. 95 | 96 | ## Examples 97 | 98 | iex> data = %{ 99 | ...> user: %{ 100 | ...> first_name: "James", 101 | ...> last_name: "Kirk", 102 | ...> crew: [ 103 | ...> %{name: "Spock", serial_number: "S 179-276 SP"}, 104 | ...> %{name: "Scotty", serial_number: "SE 19754 T"} 105 | ...> ] 106 | ...> } 107 | ...> } 108 | iex> Casex.to_camel_case(data) 109 | %{ 110 | "user" => %{ 111 | "firstName" => "James", 112 | "lastName" => "Kirk", 113 | "crew" => [ 114 | %{"name" => "Spock", "serialNumber" => "S 179-276 SP"}, 115 | %{"name" => "Scotty", "serialNumber" => "SE 19754 T"} 116 | ] 117 | } 118 | } 119 | 120 | """ 121 | @spec to_camel_case(data :: term()) :: term() 122 | def to_camel_case(data) when is_map(data) do 123 | result = Serializable.serialize(data) 124 | 125 | case result do 126 | {map, dict} -> 127 | map 128 | |> Enum.map(fn {key, value} -> 129 | {Map.get_lazy(dict, key, fn -> camel_case(key) end), to_camel_case(value)} 130 | end) 131 | |> Enum.into(%{}) 132 | 133 | map -> 134 | map 135 | |> Enum.map(fn {key, value} -> {camel_case(key), to_camel_case(value)} end) 136 | |> Enum.into(%{}) 137 | end 138 | rescue 139 | Protocol.UndefinedError -> data 140 | end 141 | 142 | def to_camel_case(data) when is_list(data) do 143 | Enum.map(data, &to_camel_case/1) 144 | end 145 | 146 | def to_camel_case(data), do: Serializable.serialize(data) 147 | 148 | defp camel_case(value) when is_atom(value) do 149 | value 150 | |> to_string() 151 | |> camel_case() 152 | end 153 | 154 | defp camel_case(value) when is_binary(value) do 155 | Recase.to_camel(value) 156 | end 157 | end 158 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------