Last active
April 5, 2024 21:17
-
-
Save jorgevilaca82/9e0d3b0d30b4a586f3b47e401be02504 to your computer and use it in GitHub Desktop.
Elixir map user attributes to meet external service format
This file contains hidden or 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 UserMapperFunctions do | |
def map_my_address(%{ | |
address: address, | |
city: city, | |
province: province, | |
country: country, | |
postalCode: postalCode | |
}) do | |
"#{address}, #{city}, #{province}, #{country}, #{postalCode}" | |
end | |
end | |
mappings = %{ | |
user_name: :login, | |
dob: {:date_of_birth, fn value -> Date.from_iso8601!(value) end}, | |
address: {nil, &UserMapperFunctions.map_my_address/1}, | |
other_address: {:my_address, %{province: :state, country: :land}} | |
} | |
user = %{ | |
dob: "1990-01-01", | |
user_name: "John", | |
address: %{ | |
address: "1st Street", | |
city: "Vancouver", | |
province: "ON", | |
country: "CA", | |
postalCode: "999" | |
}, | |
other_address: %{ | |
address: "1st Street", | |
city: "Vancouver", | |
province: "ON", | |
country: "CA", | |
postalCode: "999" | |
} | |
} | |
defmodule Mapper do | |
def map(mappings, map) do | |
for {key, new_key} <- mappings, into: %{} do | |
{new_key, map_or_op} = get_new_key_and_op(new_key, key) |> IO.inspect() | |
if Map.has_key?(map, key), do: transform(map[key], new_key, map_or_op) | |
end | |
end | |
def get_new_key_and_op(new_key, current_key) do | |
case new_key do | |
{nil, op} when is_function(op) -> {current_key, op} | |
{new_key, op} when is_function(op) -> {new_key, op} | |
{nil, map} when is_map(map) -> {current_key, map} | |
{new_key, map} when is_map(map) -> {new_key, map} | |
nil -> {current_key, nil} | |
_ -> {new_key, nil} | |
end | |
end | |
defp transform(value, new_key, nil), do: {new_key, value} | |
defp transform(value, new_key, op) when is_function(op), do: {new_key, op.(value)} | |
defp transform(value, new_key, map) when is_map(map), do: {new_key, map(map, value)} | |
end | |
mappings | |
|> Mapper.map(user) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment