shortnr/lib/router.ex

56 lines
1.2 KiB
Elixir
Raw Normal View History

2019-12-08 02:34:58 +00:00
defmodule Shortnr.Router do
use Plug.ErrorHandler
use Plug.Router
require Logger
alias Shortnr.Transport.{Text, HTTP}
2019-12-08 18:44:04 +00:00
alias Shortnr.URL
2019-12-08 02:34:58 +00:00
plug(Plug.Logger, log: :debug)
plug(:match)
plug(:dispatch)
2019-12-08 18:44:04 +00:00
post "/urls/:url" do
{:ok, url, conn}
|> HTTP.handle(&URL.create(&1, URL.Repo.ETS))
2019-12-08 18:44:04 +00:00
|> Text.encode_response()
|> HTTP.send(:created, conn)
2019-12-08 02:34:58 +00:00
end
2019-12-08 18:44:04 +00:00
get "/urls" do
{:ok, :ignore, conn}
|> HTTP.handle(fn -> URL.list(URL.Repo.ETS) end)
2019-12-08 18:44:04 +00:00
|> Text.encode_response()
|> HTTP.send(:ok, conn)
2019-12-08 18:44:04 +00:00
end
get "/:id" do
{:ok, id, conn}
|> HTTP.handle(&URL.get(&1, URL.Repo.ETS))
2019-12-08 18:44:04 +00:00
|> Text.encode_response()
|> HTTP.send(:found, conn)
2019-12-08 18:44:04 +00:00
end
delete "/:id" do
{:ok, id, conn}
|> HTTP.handle(&URL.delete(&1, URL.Repo.ETS))
|> Text.encode_response()
|> HTTP.send(:ok, conn)
end
2019-12-08 02:34:58 +00:00
match _ do
{:error, {:not_found, "route not found"}, conn}
2019-12-08 18:44:04 +00:00
|> Text.encode_response()
|> HTTP.send(:ignore, conn)
2019-12-08 02:34:58 +00:00
end
def handle_errors(conn, %{kind: _kind, reason: reason, stack: stack}) do
Logger.error(reason, stack: stack)
2019-12-08 02:34:58 +00:00
{:error, {:internal_server_error, "internal server error"}, conn}
2019-12-08 18:44:04 +00:00
|> Text.encode_response()
|> HTTP.send(:ignore, conn)
2019-12-08 02:34:58 +00:00
end
end