Kase.Plug.ConvertKeys (kase v1.1.3)
A Plug for converting the casing of request and response keys.
This plug allows you to convert the keys of incoming JSON requests
and outgoing JSON responses to various casing styles such as
snake_case
, camelCase
, PascalCase
, etc.
Usage
To use this plug, you can either add it to your router or directly in a controller.
In Your Router
You can use the plug in your router to apply it to specific routes or all routes. Here's how you can do that:
defmodule MyAppWeb.Router do
use MyAppWeb, :router
pipeline :api do
plug Kase.Plug.ConvertKeys
end
scope "/api", MyAppWeb do
pipe_through :api
get "/example", ExampleController, :index
end
end
In a Controller
defmodule MyAppWeb.ExampleController do
use MyAppWeb, :controller
plug Kase.Plug.ConvertKeys
def index(conn, _params) do
json(conn, %{some_key: "some_value"})
end
end
Options
The plug accepts the following options:
- :request_casing - Specify the casing for incoming request parameters. Accepted values include :snake_case, :camel_case, :pascal_case, etc. Defaults to :snake_case.
- :response_casing - Specify the casing for outgoing response parameters. Similar to :request_casing, it accepts the same casing styles and defaults to :snake_case.
Example of using Options
Here’s an example of how to specify request and response casing options:
defmodule MyAppWeb.ExampleController do
use MyAppWeb, :controller
plug Kase.Plug.ConvertKeys, request_casing: :dot_case, response_casing: :train_case
def index(conn, _params) do
json(conn, %{"exampleKey" => "exampleValue"})
end
end
In this example, incoming parameters will be converted to camelCase, and outgoing responses will be in PascalCase.
Summary
Functions
Link to this function
call(conn, opts \\ [])
Converts the keys of the request body to the desired casing style.
Link to this function
init(opts)
Initializes the plug.