Skip to content

Commit

Permalink
Implement as_map protocol (WIP)
Browse files Browse the repository at this point in the history
  • Loading branch information
mkrogemann committed Aug 29, 2016
1 parent e3d490d commit 33c7347
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
23 changes: 23 additions & 0 deletions lib/couchdb_connector/as_map.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
defprotocol AsMap do
@moduledoc """
"""
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
{:error, :invalid} ->
raise RuntimeError, message:
"""
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}"
end
end
end
31 changes: 31 additions & 0 deletions test/couchdb_connector/as_map_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
defmodule Couchdb.Connector.AsMapTest do
use ExUnit.Case

import AsMap

test "as_map/2 with invalid json string should raise RuntimeError" 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"}
""", fn -> as_map(invalid) end)
end

test "as_map/2 with empty string should raise RuntimeError" do
empty = ""

assert_raise(RuntimeError, """
Document returned by CouchDB is invalid
json:
""",
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
end

0 comments on commit 33c7347

Please sign in to comment.