Created
December 14, 2018 17:56
-
-
Save abuiles/eb2d2bb0409a757bc13bf5cdeb4e79e0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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