First working iteration of shortnr api

This commit is contained in:
mitchell 2019-12-08 13:44:04 -05:00
parent 7ff70d452a
commit 9ee9eddbfa
8 changed files with 147 additions and 12 deletions

20
lib/url/repo/dets.ex Normal file
View file

@ -0,0 +1,20 @@
defmodule Shortnr.URL.Repo.DETS do
@behaviour Shortnr.URL.Repo
@impl true
def get(key) do
{:ok, :dets.lookup(:urls, key) |> List.first() |> elem(1)}
end
@impl true
def put(url) do
:ok = :dets.insert(:urls, {url.id, url})
:ok
end
@impl true
def list() do
resp = :dets.select(:urls, [{:"$1", [], [:"$1"]}])
{:ok, resp |> Enum.map(&elem(&1, 1))}
end
end

8
lib/url/repo/repo.ex Normal file
View file

@ -0,0 +1,8 @@
defmodule Shortnr.URL.Repo do
alias Shortnr.URL
alias Shortnr.Transport
@callback put(URL.t()) :: :ok | Transport.error()
@callback get(String.t()) :: {:ok, URL.t()} | Transport.error()
@callback list() :: {:ok, list(URL.t())} | Transport.error()
end

46
lib/url/url.ex Normal file
View file

@ -0,0 +1,46 @@
defmodule Shortnr.URL do
alias Shortnr.Transport
alias Shortnr.URL
defstruct id:
for(
_ <- 0..7,
into: "",
do:
Enum.random(
String.codepoints(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXWYZ0123456789"
)
)
),
created_at: DateTime.utc_now(),
updated_at: DateTime.utc_now(),
url: %URI{}
@type t :: %__MODULE__{id: String.t(), url: URI.t()}
@spec create(String.t(), module()) :: {:ok, String.t()} | Transport.error()
def create(url, repo) do
url_struct = %URL{url: URI.parse(url)}
:ok = repo.put(url_struct)
{:ok, url_struct.id}
end
@spec get(String.t(), module()) :: {:ok, URL.t()} | Transport.error()
def get(key, repo) do
{:ok, _} = repo.get(key)
end
@spec list(module()) :: {:ok, list(URL.t())} | Transport.error()
def list(repo) do
{:ok, _} = repo.list
end
defimpl String.Chars do
alias Shortnr.URL
@spec to_string(URL.t()) :: String.t()
def to_string(url) do
"id=#{url.id} created=#{url.created_at} updated=#{url.updated_at} url=#{url.url}"
end
end
end