Skip to content

Commit

Permalink
Fixed subscription, added a subscription test
Browse files Browse the repository at this point in the history
Subscription is async and therefore must use cast, forgot about that
in the interface. Also if there were not parameters encoding wasn't
working right, so that's also fixed now
  • Loading branch information
vaartis committed Apr 10, 2018
1 parent 53c9777 commit 29f5e86
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 4 deletions.
3 changes: 1 addition & 2 deletions lib/changes_communicator.ex
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,8 @@ defmodule CouchDBEx.Worker.ChangesCommunicator do
selector: pre_final_opts[:selector]
}
|> Enum.filter(fn {_, v} -> not is_nil(v) end)
|> (fn m -> if(Enum.empty?(m), do: "", else: m) end).()
|> Enum.into(%{})
|> Poison.encode!
maybe_body = if Enum.empty?(maybe_body), do: "", else: Poison.encode!(maybe_body)

final_opts =
pre_final_opts
Expand Down
4 changes: 2 additions & 2 deletions lib/couchdb_ex.ex
Original file line number Diff line number Diff line change
Expand Up @@ -375,14 +375,14 @@ defmodule CouchDBEx do
trying to change it **WILL RAISE a RuntimeError**
"""
def changes_sub(db, modname, watcher_name, opts \\ []) do
GenServer.call(CouchDBEx.Worker, {:changes_sub, db, modname, watcher_name, opts})
GenServer.cast(CouchDBEx.Worker, {:changes_sub, db, modname, watcher_name, opts})
end

@doc """
Unsubscribe the `modname` watcher from changes in the database.
`modname` is the module's name as known to the supervisor, not the actual running module.
"""
def changes_unsub(modname), do: GenServer.call(CouchDBEx.Worker, {:changes_unsub, modname})
def changes_unsub(modname), do: GenServer.cast(CouchDBEx.Worker, {:changes_unsub, modname})

end
43 changes: 43 additions & 0 deletions test/couchdb_ex_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -154,4 +154,47 @@ defmodule CouchDBExTest do
)
end

test "subscribing works" do

defmodule ChangesTest do
use GenServer

def start_link(opts) do
GenServer.start_link(__MODULE__, nil, opts)
end

def init(_) do
{:ok, nil}
end

def handle_info({:couchdb_change, msg}, _) do
{:noreply, msg}
end

def handle_call(:get, _from, state) do
{:reply, state, state}
end

end

seed = Integer.to_string(ExUnit.configuration[:seed])

CouchDBEx.changes_sub("couchdb-ex-test", ChangesTest, ChangesTest)

CouchDBEx.document_insert_one(%{data: seed}, "couchdb-ex-test")

# Need to wait a little, it never spawns immidietly
Process.sleep(100)

assert Enum.count(Supervisor.which_children(CouchDBEx.Worker.ChangesCommunicator.Supervisor)) == 1

%{"doc" => %{"data" => ^seed}} = GenServer.call(ChangesTest, :get)

CouchDBEx.changes_unsub(ChangesTest)

# Just to be safe
Process.sleep(100)

assert Enum.count(Supervisor.which_children(CouchDBEx.Worker.ChangesCommunicator.Supervisor)) == 0
end
end

0 comments on commit 29f5e86

Please sign in to comment.