Casex v0.4.2 Casex View Source

Simple case conversion for web applications. Easily decodes camelCase body payloads to snake_case and response payloads from camelCase to snake_case. Useful to maintain to expose your API in camelCase but keep internally the elixir naming conventions.

It leverages recase to provide case conversions without relying on the Macro module and easily integrates with plug-based applications.

Phoenix Integration

  1. Add Casex.CamelCaseDecoderPlug to your api pipeline:
# router.ex
pipeline :api do
  plug :accepts, ["json"]
  plug Casex.CamelCaseDecoderPlug
end

Now, all request bodies and params will be converted to snake case.

  1. Add Casex.CamelCaseEncoder as json format encoder for phoenix:
# config.exs
config :phoenix, :format_encoders, json: Casex.CamelCaseEncoder

Now all outcoming json response bodies will be converted to camel case.

Link to this section Summary

Functions

Converts all keys of a map to camel case. If the map is a struct with no Enumerable implementation the value is returned without convertion.

Converts all keys of a map to snake case. If the map is a struct with no Enumerable implementation the value is returned without convertion.

Link to this section Functions

Link to this function

to_camel_case(data)

View Source
to_camel_case(data :: term()) :: term()

Converts all keys of a map to camel case. If the map is a struct with no Enumerable implementation the value is returned without convertion.

Examples

iex> data = %{
...>   user: %{
...>     first_name: "James",
...>     last_name: "Kirk",
...>     crew: [
...>       %{name: "Spock", serial_number: "S 179-276 SP"},
...>       %{name: "Scotty", serial_number: "SE 19754 T"}
...>     ]
...>   }
...> }
iex> Casex.to_camel_case(data)
%{
  "user" => %{
    "firstName" => "James",
    "lastName" => "Kirk",
    "crew" => [
      %{"name" => "Spock", "serialNumber" => "S 179-276 SP"},
      %{"name" => "Scotty", "serialNumber" => "SE 19754 T"}
    ]
  }
}
Link to this function

to_snake_case(data)

View Source
to_snake_case(data :: term()) :: term()

Converts all keys of a map to snake case. If the map is a struct with no Enumerable implementation the value is returned without convertion.

Examples

iex> data = %{
...>   "user" => %{
...>     "firstName" => "James",
...>     "lastName" => "Kirk",
...>     "crew" => [
...>       %{"name" => "Spock", "serialNumber" => "S 179-276 SP"},
...>       %{"name" => "Scotty", "serialNumber" => "SE 19754 T"}
...>     ]
...>   }
...> }
iex> Casex.to_snake_case(data)
%{
  "user" => %{
    "first_name" => "James",
    "last_name" => "Kirk",
    "crew" => [
      %{"name" => "Spock", "serial_number" => "S 179-276 SP"},
      %{"name" => "Scotty", "serial_number" => "SE 19754 T"}
    ]
  }
}