Skip to content

Commit 0c6fc88

Browse files
bkilshawryanwinchester
authored andcommitted
Automatically convert structs to maps
1 parent f43315c commit 0c6fc88

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed

lib/data_mapper.ex

+15-7
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,14 @@ defmodule DataMapper do
4545
def map(input) do
4646
input
4747
|> pre_map_transform()
48+
|> maybe_struct_to_map()
4849
|> map(unquote(mappings))
4950
|> post_map_transform()
5051
end
5152

53+
def maybe_struct_to_map(value) when is_struct(value), do: Map.from_struct(value)
54+
def maybe_struct_to_map(value), do: value
55+
5256
## Callbacks
5357

5458
@doc """
@@ -57,14 +61,18 @@ defmodule DataMapper do
5761
@impl true
5862
@spec map(input :: map() | keyword(), mappings :: map()) :: map()
5963
def map(input, mappings) do
60-
Enum.into(mappings, %{}, fn
61-
# Handle a nested map.
62-
{from_key, sub_mappings} when is_map(sub_mappings) ->
63-
map(input[from_key], sub_mappings)
64+
Enum.reduce(mappings, %{}, fn
65+
# # Handle a nested map.
66+
# # This part needs to be re-worked. It's broken.
67+
# {from_key, {to_key, sub_mappings}}, acc when is_map(sub_mappings) ->
68+
# Map.put(acc, to_key, map(input[from_key], sub_mappings))
6469

6570
# The normal case, mapping the input key to the output key.
66-
{from_key, to_key} ->
67-
map_field({to_key, input[from_key]})
71+
{from_key, to_key}, acc ->
72+
Map.put(acc, to_key, map_field({from_key, input[from_key]}))
73+
74+
_, acc ->
75+
acc
6876
end)
6977
end
7078

@@ -73,7 +81,7 @@ defmodule DataMapper do
7381
"""
7482
@impl true
7583
@spec map_field({atom, any}) :: {atom, any}
76-
def map_field(field), do: field
84+
def map_field({_field, value}), do: value
7785

7886
@doc """
7987
Transform the list before mapping.

0 commit comments

Comments
 (0)