feat: implement custom URLs

Signed-off-by: Amogh Lele <amolele@gmail.com>
This commit is contained in:
Amogh Lele 2022-05-28 10:29:47 +05:30
parent 5a0995b991
commit 106ae8398e
No known key found for this signature in database
GPG Key ID: 8FF3CF17CA7CFABD
4 changed files with 26 additions and 4 deletions

View File

@ -16,5 +16,6 @@ defmodule Ketbin.Pastes.Paste do
paste
|> cast(attrs, [:is_url, :content, :id, :belongs_to])
|> validate_required([:is_url, :content])
|> unique_constraint(:id, name: :pastes_pkey)
end
end

View File

@ -50,8 +50,12 @@ defmodule KetbinWeb.PageController do
end
def create(%{assigns: %{current_user: current_user}} = conn, %{"paste" => paste_params}) do
# generate phonetic key
id = Utils.generate_key()
# if custom url exists, use it as id, else generate phonetic id
id =
case Map.get(paste_params, "custom_url", "") do
custom_url when custom_url != "" -> custom_url
_ -> Utils.generate_key()
end
# check if content is a url
is_url =
@ -80,9 +84,15 @@ defmodule KetbinWeb.PageController do
# something went wrong, bail
{:error, %Ecto.Changeset{} = changeset} ->
case changeset.errors[:id] do
{"has already been taken", _} ->
render(conn, "index.html", changeset: changeset, already_taken: true)
_ ->
render(conn, "index.html", changeset: changeset)
end
end
end
def edit(conn, %{"id" => id}) do
paste = Pastes.get_paste!(id)

View File

@ -1 +1 @@
<%= render "form.html", Map.put(assigns, :action, Routes.page_path(@conn, :update, @paste)) %>
<%= render "form.html", Map.put(assigns, :action, Routes.page_path(@conn, :update, @paste)) |> Map.put(:is_edit, true) %>

View File

@ -13,9 +13,20 @@
</div>
<% end %>
<%= if assigns[:already_taken] do %>
<div class="w-full text-center bg-amber">
<p>This custom URL has already been taken.</p>
</div>
<% end %>
<div class="w-full h-full">
<%= textarea f, :content, [class: "w-full h-full px-6 py-4 outline-none bg-light-grey font-bold resize-none", placeholder: "> Paste, save, share! (Pasting just a URL will shorten it!)"] %>
<div class="flex absolute top-0 right-0 p-4">
<%= if @current_user && !assigns[:is_edit] do %>
<div>
<%= text_input f, :custom_url, [class: "px-2 mr-2 outline-none text-black px-2 py-1", placeholder: "Custom URL"] %>
</div>
<% end %>
<button type="submit">
<svg
class="h-6 w-6 cursor-pointer fill-current text-white hover:text-amber"