Preparatory work
This commit is contained in:
parent
a22ba724df
commit
386a331956
9 changed files with 217 additions and 1 deletions
20
lib/birdy_chat_web/api/messages/controller.ex
Normal file
20
lib/birdy_chat_web/api/messages/controller.ex
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
defmodule BirdyChatWeb.Api.Messages.Controller do
|
||||
use BirdyChatWeb, :controller
|
||||
|
||||
def create(conn, params) do
|
||||
case BirdyChat.Message.validate(params) do
|
||||
{:ok, changeset} ->
|
||||
case BirdyChat.Message.write(changeset.changes) do
|
||||
{:ok, msg} ->
|
||||
conn
|
||||
|> put_status(:created)
|
||||
|> render(:create, message: msg)
|
||||
end
|
||||
|
||||
{:error, changeset} ->
|
||||
conn
|
||||
|> put_status(:unprocessable_entity)
|
||||
|> render(:error, changeset: changeset)
|
||||
end
|
||||
end
|
||||
end
|
||||
14
lib/birdy_chat_web/api/messages/json.ex
Normal file
14
lib/birdy_chat_web/api/messages/json.ex
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
defmodule BirdyChatWeb.Api.Messages.JSON do
|
||||
def render("create.json", %{message: message}) do
|
||||
message
|
||||
end
|
||||
|
||||
def render("error.json", %{changeset: changeset}) do
|
||||
errors = Ecto.Changeset.traverse_errors(changeset, &get_error/1)
|
||||
%{errors: errors}
|
||||
end
|
||||
|
||||
def get_error({msg, opts}) do
|
||||
Gettext.dgettext(BirdyChatWeb.Gettext, "errors", msg, opts)
|
||||
end
|
||||
end
|
||||
|
|
@ -20,6 +20,12 @@ defmodule BirdyChatWeb.Router do
|
|||
get "/", PageController, :home
|
||||
end
|
||||
|
||||
scope "/api", BirdyChatWeb.Api do
|
||||
pipe_through [:api]
|
||||
|
||||
post "/messages", Messages.Controller, :create
|
||||
end
|
||||
|
||||
# Other scopes may use custom stacks.
|
||||
# scope "/api", BirdyChatWeb do
|
||||
# pipe_through :api
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue