2019-12-08 02:34:58 +00:00
|
|
|
defmodule Shortnr.Router do
|
2019-12-31 02:50:39 +00:00
|
|
|
@moduledoc """
|
|
|
|
This module contains the Router for the Shortnr application. Do not import, other than
|
|
|
|
Application entry.
|
|
|
|
"""
|
2019-12-08 02:34:58 +00:00
|
|
|
use Plug.ErrorHandler
|
|
|
|
use Plug.Router
|
|
|
|
|
|
|
|
require Logger
|
|
|
|
|
2019-12-31 02:50:39 +00:00
|
|
|
alias Shortnr.Transport.{HTTP, Text}
|
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)
|
|
|
|
|
2020-01-01 23:11:38 +00:00
|
|
|
get "/" do
|
|
|
|
conn
|
|
|
|
|> HTTP.wrap()
|
|
|
|
|> HTTP.handle(fn -> URL.list(URL.Repo.ETS) end)
|
|
|
|
|> Text.encode_response()
|
|
|
|
|> HTTP.send(:ok)
|
|
|
|
end
|
|
|
|
|
2019-12-08 18:44:04 +00:00
|
|
|
post "/urls/:url" do
|
2020-01-01 23:11:38 +00:00
|
|
|
conn
|
|
|
|
|> HTTP.wrap(url)
|
2019-12-26 21:11:43 +00:00
|
|
|
|> HTTP.handle(&URL.create(&1, URL.Repo.ETS))
|
2019-12-08 18:44:04 +00:00
|
|
|
|> Text.encode_response()
|
2020-01-01 23:11:38 +00:00
|
|
|
|> HTTP.send(:created)
|
2019-12-08 02:34:58 +00:00
|
|
|
end
|
|
|
|
|
2019-12-08 18:44:04 +00:00
|
|
|
get "/urls" do
|
2020-01-01 23:11:38 +00:00
|
|
|
conn
|
|
|
|
|> HTTP.wrap()
|
2019-12-26 21:11:43 +00:00
|
|
|
|> HTTP.handle(fn -> URL.list(URL.Repo.ETS) end)
|
2019-12-08 18:44:04 +00:00
|
|
|
|> Text.encode_response()
|
2020-01-01 23:11:38 +00:00
|
|
|
|> HTTP.send(:ok)
|
2019-12-08 18:44:04 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
get "/:id" do
|
2020-01-01 23:11:38 +00:00
|
|
|
conn
|
|
|
|
|> HTTP.wrap(id)
|
2019-12-26 21:11:43 +00:00
|
|
|
|> HTTP.handle(&URL.get(&1, URL.Repo.ETS))
|
2019-12-08 18:44:04 +00:00
|
|
|
|> Text.encode_response()
|
2020-01-01 23:11:38 +00:00
|
|
|
|> HTTP.send(:found)
|
2019-12-08 18:44:04 +00:00
|
|
|
end
|
|
|
|
|
2019-12-09 02:39:11 +00:00
|
|
|
delete "/:id" do
|
2020-01-01 23:11:38 +00:00
|
|
|
conn
|
|
|
|
|> HTTP.wrap(id)
|
2019-12-26 21:11:43 +00:00
|
|
|
|> HTTP.handle(&URL.delete(&1, URL.Repo.ETS))
|
2019-12-09 02:39:11 +00:00
|
|
|
|> Text.encode_response()
|
2020-01-01 23:11:38 +00:00
|
|
|
|> HTTP.send(:ok)
|
2019-12-09 02:39:11 +00:00
|
|
|
end
|
|
|
|
|
2019-12-08 02:34:58 +00:00
|
|
|
match _ do
|
2020-01-01 23:11:38 +00:00
|
|
|
conn
|
|
|
|
|> HTTP.wrap({:not_found, "route not found"})
|
|
|
|
|> HTTP.send()
|
2019-12-08 02:34:58 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def handle_errors(conn, %{kind: _kind, reason: reason, stack: stack}) do
|
2020-01-01 23:11:38 +00:00
|
|
|
Logger.error(inspect(reason), stack: ~s|"#{inspect(stack)}"|)
|
2019-12-08 02:34:58 +00:00
|
|
|
|
2020-01-01 23:11:38 +00:00
|
|
|
conn
|
|
|
|
|> HTTP.wrap({:internal_server_error, "internal server error"})
|
|
|
|
|> HTTP.send()
|
2019-12-08 02:34:58 +00:00
|
|
|
end
|
|
|
|
end
|