mirror of
https://github.com/mitchell/shortnr.git
synced 2025-12-31 18:37:22 +00:00
Add Endpoints behaviour and refactor router and related methods
This commit is contained in:
parent
1502d10cdc
commit
98684feb2d
8 changed files with 98 additions and 62 deletions
45
lib/url/endpoints.ex
Normal file
45
lib/url/endpoints.ex
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
defmodule Shortnr.URL.Endpoints do
|
||||
@moduledoc """
|
||||
This module implements the Endpoints behaviour.
|
||||
"""
|
||||
alias Shortnr.Transport.{HTTP, Text}
|
||||
alias Shortnr.Transport.HTTP.Endpoints
|
||||
alias Shortnr.URL
|
||||
|
||||
@behaviour Endpoints
|
||||
|
||||
@impl Endpoints
|
||||
def select(conn, name, arg \\ nil)
|
||||
|
||||
def select(conn, :list, _arg) do
|
||||
conn
|
||||
|> HTTP.wrap()
|
||||
|> HTTP.handle(fn -> URL.list(URL.Repo.ETS) end)
|
||||
|> Text.encode()
|
||||
|> HTTP.send(:ok)
|
||||
end
|
||||
|
||||
def select(conn, :create, url) do
|
||||
conn
|
||||
|> HTTP.wrap(url)
|
||||
|> HTTP.handle(&URL.create(&1, URL.Repo.ETS))
|
||||
|> Text.encode()
|
||||
|> HTTP.send(:created)
|
||||
end
|
||||
|
||||
def select(conn, :get, id) do
|
||||
conn
|
||||
|> HTTP.wrap(id)
|
||||
|> HTTP.handle(&URL.get(&1, URL.Repo.ETS))
|
||||
|> Text.encode()
|
||||
|> HTTP.send(:found)
|
||||
end
|
||||
|
||||
def select(conn, :delete, id) do
|
||||
conn
|
||||
|> HTTP.wrap(id)
|
||||
|> HTTP.handle(&URL.delete(&1, URL.Repo.ETS))
|
||||
|> Text.encode()
|
||||
|> HTTP.send(:ok)
|
||||
end
|
||||
end
|
||||
|
|
@ -2,10 +2,11 @@ defmodule Shortnr.URL.Repo.ETS do
|
|||
@moduledoc """
|
||||
This module is an implemention of the Repo behaviour using the Erlang ETS library.
|
||||
"""
|
||||
alias Shortnr.URL.Repo
|
||||
|
||||
@behaviour Shortnr.URL.Repo
|
||||
@behaviour Repo
|
||||
|
||||
@impl true
|
||||
@impl Repo
|
||||
def get(key) do
|
||||
case ets().lookup(:urls, key) |> List.first() do
|
||||
{_, url} -> {:ok, url}
|
||||
|
|
@ -13,25 +14,25 @@ defmodule Shortnr.URL.Repo.ETS do
|
|||
end
|
||||
end
|
||||
|
||||
@impl true
|
||||
@impl Repo
|
||||
def put(url) do
|
||||
:ok = ets().insert(:urls, {url.id, url})
|
||||
:ok
|
||||
end
|
||||
|
||||
@impl true
|
||||
@impl Repo
|
||||
def list do
|
||||
resp = ets().select(:urls, [{:"$1", [], [:"$1"]}])
|
||||
{:ok, resp |> Enum.map(&elem(&1, 1))}
|
||||
end
|
||||
|
||||
@impl true
|
||||
@impl Repo
|
||||
def delete(key) do
|
||||
:ok = ets().delete(:urls, key)
|
||||
:ok
|
||||
end
|
||||
|
||||
@impl true
|
||||
@impl Repo
|
||||
def reset do
|
||||
:ok = ets().delete_all_objects(:urls)
|
||||
end
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue