diff --git a/lib/httparrot.ex b/lib/httparrot.ex index 696ae83..9bf3ea8 100644 --- a/lib/httparrot.ex +++ b/lib/httparrot.ex @@ -10,6 +10,7 @@ defmodule HTTParrot do {'/post', HTTParrot.PostHandler, []}, {'/status/:code', HTTParrot.StatusCodeHandler, []}, {'/redirect-to', HTTParrot.RedirectToHandler, []}, + {'/cookies', HTTParrot.CookiesHandler, []}, {'/basic-auth/:user/:passwd', HTTParrot.BasicAuthHandler, []}, {'/html', :cowboy_static, {:priv_file, :httparrot, "html.html"}} ] } ]) diff --git a/lib/httparrot/cookies_handler.ex b/lib/httparrot/cookies_handler.ex new file mode 100644 index 0000000..6d65f51 --- /dev/null +++ b/lib/httparrot/cookies_handler.ex @@ -0,0 +1,25 @@ +defmodule HTTParrot.CookiesHandler do + def init(_transport, _req, _opts) do + {:upgrade, :protocol, :cowboy_rest} + end + + def allowed_methods(req, state) do + {["GET"], req, state} + end + + def content_types_provided(req, state) do + {[{{"application", "json", []}, :get_json}], req, state} + end + + def get_json(req, state) do + {cookies, req} = :cowboy_req.cookies(req) + if cookies == [], do: cookies = [{}] + {response(cookies), req, state} + end + + defp response(cookies) do + [cookies: cookies] |> JSEX.encode! + end + + def terminate(_, _, _), do: :ok +end diff --git a/test/cookies_handler_test.exs b/test/cookies_handler_test.exs new file mode 100644 index 0000000..6f30288 --- /dev/null +++ b/test/cookies_handler_test.exs @@ -0,0 +1,25 @@ +defmodule HTTParrot.CookiesHandlerTest do + use ExUnit.Case + import :meck + import HTTParrot.CookiesHandler + + setup do + new :cowboy_req + new JSEX + end + + teardown do + unload :cowboy_req + unload JSEX + end + + test "returns a JSON with all the cookies o/" do + expect(:cowboy_req, :cookies, 1, {[k1: :v1], :req2}) + expect(JSEX, :encode!, [{[[cookies: [k1: :v1]]], :json}]) + + assert get_json(:req1, :state) == {:json, :req2, :state} + + assert validate :cowboy_req + assert validate JSEX + end +end