Skip to content

Commit

Permalink
Merge f37c6b4 into 34796e6
Browse files Browse the repository at this point in the history
  • Loading branch information
imranismail committed Apr 12, 2017
2 parents 34796e6 + f37c6b4 commit aed296b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
36 changes: 34 additions & 2 deletions lib/maxwell/conn.ex
Expand Up @@ -47,7 +47,8 @@ defmodule Maxwell.Conn do
req_body: iodata | Map.t,
status: non_neg_integer | nil,
resp_headers: %{binary => binary},
resp_body: iodata | Map.t
resp_body: iodata | Map.t,
private: Map.t
}

defstruct state: :unsent,
Expand All @@ -60,7 +61,8 @@ defmodule Maxwell.Conn do
opts: [],
status: nil,
resp_headers: %{},
resp_body: ""
resp_body: "",
private: %{}

alias Maxwell.{Conn, Query}

Expand Down Expand Up @@ -414,6 +416,36 @@ defmodule Maxwell.Conn do
def get_resp_body(%Conn{resp_body: body}, keys) when is_list(keys), do: get_in(body, keys)
def get_resp_body(%Conn{resp_body: body}, key), do: body[key]


@doc """
Set a private value. If it already exists, it is updated.
### Examples
iex> %Maxwell.Conn{private: %{}}
|> put_private(:user_id, "zhongwencool")
%Maxwell.Conn{private: %{user_id: "zhongwencool"}}
"""
@spec put_private(Conn.t, Atom.t, term()) :: Conn.t
def put_private(%Conn{private: private} = conn, key, value) do
new_private = Map.put(private, key, value)
%{conn | private: new_private}
end

@doc """
Get a private value
### Examples
iex> %Maxwell.Conn{private: %{user_id: "zhongwencool"}}
|> get_private(:user_id)
"zhongwencool"
"""
@spec get_private(Conn.t, Atom.t) :: term()
def get_private(%Conn{private: private}, key) do
Map.get(private, key)
end

defimpl Inspect, for: Conn do
def inspect(conn, opts) do
Inspect.Any.inspect(conn, opts)
Expand Down
9 changes: 9 additions & 0 deletions test/maxwell/conn_test.exs
Expand Up @@ -234,4 +234,13 @@ defmodule ConnTest do
get_resp_body(%Conn{state: :unsent, resp_body: %{"foo" => "bar"}}, "foo")
end
end

test "put_private/3" do
assert put_private(%Conn{}, :user_id, "zhongwencool") == %Conn{private: %{user_id: "zhongwencool"}}
end

test "get_private/2" do
assert get_private(%Conn{}, :user_id) == nil
assert get_private(%Conn{private: %{user_id: "zhongwencool"}}, :user_id) == "zhongwencool"
end
end

0 comments on commit aed296b

Please sign in to comment.