Add url delete endpoint and minor refactors

This commit is contained in:
mitchell 2019-12-08 21:39:11 -05:00
parent 9ee9eddbfa
commit faaf12ba42
5 changed files with 32 additions and 12 deletions

View File

@ -32,6 +32,13 @@ defmodule Shortnr.Router do
|> Http.send(:found, conn)
end
delete "/:id" do
{:ok, id, conn}
|> Http.handle(&URL.delete(&1, URL.Repo.DETS))
|> Text.encode_response()
|> Http.send(:ok, conn)
end
match _ do
{:error, {:not_found, "route not found"}, conn}
|> Text.encode_response()

View File

@ -17,4 +17,10 @@ defmodule Shortnr.URL.Repo.DETS do
resp = :dets.select(:urls, [{:"$1", [], [:"$1"]}])
{:ok, resp |> Enum.map(&elem(&1, 1))}
end
@impl true
def delete(key) do
:ok = :dets.delete(:urls, key)
:ok
end
end

View File

@ -4,5 +4,6 @@ defmodule Shortnr.URL.Repo do
@callback put(URL.t()) :: :ok | Transport.error()
@callback get(String.t()) :: {:ok, URL.t()} | Transport.error()
@callback delete(String.t()) :: :ok | Transport.error()
@callback list() :: {:ok, list(URL.t())} | Transport.error()
end

View File

@ -1,18 +1,9 @@
defmodule Shortnr.URL do
alias Shortnr.Transport
alias Shortnr.URL
alias Shortnr.URL.Util
defstruct id:
for(
_ <- 0..7,
into: "",
do:
Enum.random(
String.codepoints(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXWYZ0123456789"
)
)
),
defstruct id: "",
created_at: DateTime.utc_now(),
updated_at: DateTime.utc_now(),
url: %URI{}
@ -21,7 +12,7 @@ defmodule Shortnr.URL do
@spec create(String.t(), module()) :: {:ok, String.t()} | Transport.error()
def create(url, repo) do
url_struct = %URL{url: URI.parse(url)}
url_struct = %URL{id: Util.gen_id(), url: URI.parse(url)}
:ok = repo.put(url_struct)
{:ok, url_struct.id}
end
@ -36,6 +27,12 @@ defmodule Shortnr.URL do
{:ok, _} = repo.list
end
@spec delete(String.t(), module()) :: {:ok, :ignore} | Tranpsport.error()
def delete(key, repo) do
:ok = repo.delete(key)
{:ok, "Success"}
end
defimpl String.Chars do
alias Shortnr.URL
@spec to_string(URL.t()) :: String.t()

9
lib/url/util.ex Normal file
View File

@ -0,0 +1,9 @@
defmodule Shortnr.URL.Util do
@id_chars String.codepoints("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXWYZ0123456789")
@spec gen_id() :: String.t()
def gen_id do
for _ <- 0..7,
into: "",
do: Enum.random(@id_chars)
end
end