View Source Flowy.Utils.Case (Flowy v0.1.4)

NOTE: This is a port from https://github.com/Finbits/casex

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 Flowy.Utils.Case.CamelCaseDecoderPlug to your api pipeline:
# router.ex
pipeline :api do
  plug :accepts, ["json"]
  plug Flowy.Utils.Case.CamelCaseDecoderPlug
end

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

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

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

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.

Functions

@spec 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> Flowy.Utils.Case.to_camel_case(data)
%{
  "user" => %{
    "firstName" => "James",
    "lastName" => "Kirk",
    "crew" => [
      %{"name" => "Spock", "serialNumber" => "S 179-276 SP"},
      %{"name" => "Scotty", "serialNumber" => "SE 19754 T"}
    ]
  }
}
@spec 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> Flowy.Utils.Case.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"}
    ]
  }
}