Skip to content

Instantly share code, notes, and snippets.

@abuiles
Created December 14, 2018 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abuiles/eb2d2bb0409a757bc13bf5cdeb4e79e0 to your computer and use it in GitHub Desktop.
Save abuiles/eb2d2bb0409a757bc13bf5cdeb4e79e0 to your computer and use it in GitHub Desktop.
defmodule Hub.JsonApiClient.Middleware.NormalizeAttributes do
@moduledoc """
JsonApiClient middleware to convert attributes from kebab-case to snake_case.
"""
@behaviour JsonApiClient.Middleware
alias JsonApiClient.{Request}
@impl JsonApiClient.Middleware
def call(%Request{} = request, next, _options) do
with {:ok, response} <- next.(request),
doc <- normalize_attributes(response.doc) do
{:ok, Map.put(response, :doc, doc)}
else
error -> error
end
end
defp normalize_attributes(nil), do: nil
defp normalize_attributes(
%JsonApiClient.Document{data: %JsonApiClient.Resource{attributes: attributes}} = doc
) do
attributes = convert_kebab_to_snake_case(attributes)
data = %{doc.data | attributes: attributes}
%{doc | data: data}
end
defp normalize_attributes(doc), do: doc
defp convert_kebab_to_snake_case(nil), do: nil
defp convert_kebab_to_snake_case(attributes) do
for {key, val} <- attributes,
into: %{},
do: {
key
|> String.replace("-", "_")
|> String.to_atom(),
val
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment