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)
|
|
|
|
|
2019-12-08 18:44:04 +00:00
|
|
|
post "/urls/:url" do
|
|
|
|
{:ok, url, conn}
|
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()
|
2019-12-26 21:11:43 +00:00
|
|
|
|> 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}
|
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()
|
2019-12-26 21:11:43 +00:00
|
|
|
|> HTTP.send(:ok, conn)
|
2019-12-08 18:44:04 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
get "/:id" do
|
|
|
|
{:ok, id, conn}
|
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()
|
2019-12-26 21:11:43 +00:00
|
|
|
|> HTTP.send(:found, conn)
|
2019-12-08 18:44:04 +00:00
|
|
|
end
|
|
|
|
|
2019-12-09 02:39:11 +00:00
|
|
|
delete "/:id" do
|
|
|
|
{:ok, id, conn}
|
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()
|
2019-12-26 21:11:43 +00:00
|
|
|
|> HTTP.send(:ok, conn)
|
2019-12-09 02:39:11 +00:00
|
|
|
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()
|
2019-12-26 21:11:43 +00:00
|
|
|
|> HTTP.send(:ignore, conn)
|
2019-12-08 02:34:58 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def handle_errors(conn, %{kind: _kind, reason: reason, stack: stack}) do
|
2019-12-16 04:20:21 +00:00
|
|
|
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()
|
2019-12-26 21:11:43 +00:00
|
|
|
|> HTTP.send(:ignore, conn)
|
2019-12-08 02:34:58 +00:00
|
|
|
end
|
|
|
|
end
|