@@ -40,6 +40,7 @@ defmodule EctoSync.Subscriber do
4040 events
4141 end
4242 end )
43+ |> merge_assocs ( )
4344 |> Enum . map ( fn { { watcher_identifier , id } , opts } ->
4445 do_subscribe ( watcher_identifier , id , opts )
4546 end )
@@ -60,7 +61,12 @@ defmodule EctoSync.Subscriber do
6061
6162 if self ( ) not in pids do
6263 Logger . debug ( "EventRegistry | #{ inspect ( { watcher_identifier , id } ) } " )
63- Registry . register ( EventRegistry , { encoded_identifier , id } , opts )
64+
65+ Registry . register (
66+ EventRegistry ,
67+ { encoded_identifier , id } ,
68+ opts
69+ )
6470
6571 EctoWatch . subscribe ( encoded_identifier , id )
6672 end
@@ -86,17 +92,20 @@ defmodule EctoSync.Subscriber do
8692 parent_id = primary_key ( struct )
8793 assoc_field = { related_key , parent_id }
8894 assocs = Map . get ( struct , field )
89-
90- [ { { schema , :inserted } , assoc_field } | subscribe_events ( struct ) ] ++
91- [ Enum . map ( assocs , & subscribe_events / 1 ) ]
95+ # | subscribe_events(struct)
96+ [ { { schema , :inserted } , assoc_field } ] ++ [ Enum . map ( assocs , & subscribe_events / 1 ) ]
9297 end
9398
94- def subscribe_events ( struct , % HasThrough { through: [ k | through ] } ) ,
95- do:
96- subscribe_events_assocs (
97- Map . get ( struct , k ) ,
98- through
99- )
99+ def subscribe_events ( struct , % HasThrough { through: through } = assoc ) do
100+ preloads =
101+ through
102+ |> Enum . reverse ( )
103+ |> Enum . reduce ( [ ] , fn k , acc ->
104+ [ { k , acc } ]
105+ end )
106+
107+ subscribe_events_assocs ( struct , preloads )
108+ end
100109
101110 def subscribe_events ( struct , % ManyToMany {
102111 join_through: join_through ,
@@ -264,12 +273,26 @@ defmodule EctoSync.Subscriber do
264273 subscribe_events ( parent , assoc_info )
265274 |> add_opts ( opts )
266275
267- # |> IO.inspect(label: :events)
268-
269276 subscribe_events_assocs ( value , nested , events ++ acc )
270277 end
271278 end
272279
273- defp add_opts ( list , opts ) when is_list ( list ) , do: List . flatten ( list ) |> Enum . map ( & { & 1 , opts } )
280+ defp add_opts ( list , opts ) when is_list ( list ) ,
281+ do: List . flatten ( list ) |> Enum . map ( & add_opts ( & 1 , opts ) )
282+
283+ defp add_opts ( { { { _ , _ } , _ } , _ } = tuple , _opts ) , do: tuple
274284 defp add_opts ( tuple , opts ) , do: { tuple , opts }
285+
286+ defp merge_assocs ( watchers ) do
287+ watchers
288+ |> Enum . group_by ( fn { identifier_id , _opts } -> identifier_id end , fn { _ , opts } -> opts end )
289+ |> Enum . map ( fn { watcher_identifier , opts } ->
290+ opts =
291+ Enum . reduce ( opts , [ ] , fn opt , acc ->
292+ kw_deep_merge ( acc , opt )
293+ end )
294+
295+ { watcher_identifier , opts }
296+ end )
297+ end
275298end
0 commit comments