diff --git a/lib/router.ex b/lib/router.ex index 3f7b991..ce5c1f5 100644 --- a/lib/router.ex +++ b/lib/router.ex @@ -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() diff --git a/lib/url/repo/dets.ex b/lib/url/repo/dets.ex index 3a598d1..18dae67 100644 --- a/lib/url/repo/dets.ex +++ b/lib/url/repo/dets.ex @@ -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 diff --git a/lib/url/repo/repo.ex b/lib/url/repo/repo.ex index 620c4ea..48d35d1 100644 --- a/lib/url/repo/repo.ex +++ b/lib/url/repo/repo.ex @@ -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 diff --git a/lib/url/url.ex b/lib/url/url.ex index 64cfcdf..b888184 100644 --- a/lib/url/url.ex +++ b/lib/url/url.ex @@ -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() diff --git a/lib/url/util.ex b/lib/url/util.ex new file mode 100644 index 0000000..8919e9e --- /dev/null +++ b/lib/url/util.ex @@ -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