feat(pastes): add REST routes to view and create pastes

Signed-off-by: Amogh Lele <amogh@dyte.io>
This commit is contained in:
Amogh Lele 2022-05-07 00:04:59 +05:30
parent bf50e4264d
commit 20a0b45954
No known key found for this signature in database
GPG Key ID: 56429BFA4A7B86B6
4 changed files with 73 additions and 0 deletions

View File

@ -1,6 +1,7 @@
defmodule Ketbin.Pastes.Paste do
use Ecto.Schema
import Ecto.Changeset
@derive {Jason.Encoder, only: [:content, :is_url, :belongs_to]}
@primary_key {:id, :string, autogenerate: false}
@derive {Phoenix.Param, key: :id}

View File

@ -0,0 +1,46 @@
defmodule KetbinWeb.Api.PasteController do
use KetbinWeb, :controller
alias Ketbin.Pastes
alias Ketbin.Pastes.Paste
alias Ketbin.Pastes.Utils
def show(conn, %{"id" => id}) do
[head | _tail] = String.split(id, ".")
# fetch paste from db
paste = Pastes.get_paste!(head)
render(conn, "paste.json", paste: paste)
end
def create(%{assigns: %{current_user: current_user}} = conn, %{"paste" => paste_params}) do
# generate phonetic key
id = Utils.generate_key()
# check if content is a url
is_url =
Map.get(paste_params, "content")
|> Utils.is_url?()
# put id and is_url values into changeset
paste_params =
Map.put(paste_params, "id", id)
|> Map.put("is_url", is_url)
|> Map.put("belongs_to", current_user && current_user.id)
# attempt to create a paste
case Pastes.create_paste(paste_params) do
# all good
{:ok, paste} ->
conn
|> put_status(:created)
|> render("paste.json", paste: paste)
# something went wrong, bail
{:error, %Ecto.Changeset{} = _changeset} ->
conn
|> put_status(:internal_server_error)
|> render("error.json")
end
end
end

View File

@ -14,6 +14,8 @@ defmodule KetbinWeb.Router do
pipeline :api do
plug :accepts, ["json"]
plug :fetch_session
plug :fetch_current_user
end
scope "/", KetbinWeb do
@ -42,6 +44,12 @@ defmodule KetbinWeb.Router do
put "/:id", PageController, :update
end
scope "/api", KetbinWeb.Api, as: :api do
pipe_through :api
resources "/paste", PasteController, only: [:show, :index, :create]
end
# Other scopes may use custom stacks.
# scope "/api", KetbinWeb do
# pipe_through :api

View File

@ -0,0 +1,18 @@
defmodule KetbinWeb.Api.PasteView do
use KetbinWeb, :view
def render("paste.json", %{paste: paste}) do
%{
id: paste.id,
content: paste.content,
is_url: paste.is_url
}
end
def render("error.json", _assigns) do
%{
success: false,
msg: "Something went wrong"
}
end
end