Skip to content

Instantly share code, notes, and snippets.

@jorgevilaca82
Last active April 5, 2024 21:17
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 jorgevilaca82/9e0d3b0d30b4a586f3b47e401be02504 to your computer and use it in GitHub Desktop.
Save jorgevilaca82/9e0d3b0d30b4a586f3b47e401be02504 to your computer and use it in GitHub Desktop.
Elixir map user attributes to meet external service format
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