Skip to content

Commit

Permalink
Finish implementation of as_map for BitString
Browse files Browse the repository at this point in the history
  • Loading branch information
mkrogemann committed Aug 29, 2016
1 parent 33c7347 commit 7cc5419
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 13 deletions.
13 changes: 9 additions & 4 deletions lib/couchdb_connector/as_map.ex
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
defprotocol AsMap do
@moduledoc """
This protocol provides the as_map function that translates a BitString
returned from CouchDB into a Map.
"""
def as_map(json)
end

defimpl AsMap, for: BitString do

Poison.decode("")
def as_map(json) do
case Poison.decode(json) do
{:ok, decoded} -> decoded
Expand All @@ -16,8 +16,13 @@ defimpl AsMap, for: BitString do
Document returned by CouchDB is invalid
json: #{json}
"""
{:error, reason} ->
raise RuntimeError, message: "Document returned by CouchDB is not parseable\nreason: #{elem(reason, 0)}\nchar: #{elem(reason, 1)}\njson: #{json}"
{:error, {:invalid, token}} ->
raise RuntimeError, message:
"""
Document returned by CouchDB is invalid
token: #{token}
json: #{json}
"""
end
end
end
20 changes: 11 additions & 9 deletions test/couchdb_connector/as_map_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@ defmodule Couchdb.Connector.AsMapTest do
invalid = "{\"_id\":\"foo\",\"_rev\":\"1-0f97561a543ed2e9c98a24dea818ec10\",test_key\":\"test_value\"}\n"

assert_raise(RuntimeError, """
Document returned by CouchDB is not parseable
reason: invalid
char: t
json: {"_id":"foo","_rev":"1-0f97561a543ed2e9c98a24dea818ec10",test_key":"test_value"}
Document returned by CouchDB is invalid
token: t
json: {"_id":"foo","_rev":"1-0f97561a543ed2e9c98a24dea818ec10",test_key":"test_value"}\n
""", fn -> as_map(invalid) end)
end

Expand All @@ -19,13 +18,16 @@ defmodule Couchdb.Connector.AsMapTest do

assert_raise(RuntimeError, """
Document returned by CouchDB is invalid
json:
json: #{empty}
""",
fn -> as_map(empty) end)
end

# test "as_map/2 with valid json string should return decoded Map" do
# valid = "{\"_id\":\"foo\",\"_rev\":\"1-0f97561a543ed2e9c98a24dea818ec10\",test_key\":\"test_value\"}\n"
#
# end
test "as_map/2 with valid json string should return decoded Map" do
valid = "{\"_id\":\"foo\",\"_rev\":\"1-0f97561a543ed2e9c98a24dea818ec10\",\"test_key\":\"test_value\"}\n"
decoded = as_map(valid)
assert decoded["_id"] == "foo"
assert decoded["_rev"] == "1-0f97561a543ed2e9c98a24dea818ec10"
assert decoded["test_key"] == "test_value"
end
end

0 comments on commit 7cc5419

Please sign in to comment.