Skip to content

Commit

Permalink
feat: Adding API controller and ability to create item thru API. #53
Browse files Browse the repository at this point in the history
  • Loading branch information
LuchoTurtle committed Dec 12, 2022
1 parent 043c3e9 commit 478ebf0
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 4 deletions.
3 changes: 3 additions & 0 deletions lib/app/todo/item.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ defmodule App.Todo.Item do
use Ecto.Schema
import Ecto.Changeset

@derive {Jason.Encoder, only: [:person_id, :status, :text]}
schema "items" do
field :person_id, :integer, default: 0
field :status, :integer, default: 0
Expand All @@ -15,5 +16,7 @@ defmodule App.Todo.Item do
item
|> cast(attrs, [:text, :person_id, :status])
|> validate_required([:text])
|> validate_number(:status, greater_than_or_equal_to: 0, less_than_or_equal_to: 2)
|> validate_length(:text, min: 0)
end
end
34 changes: 34 additions & 0 deletions lib/app_web/controllers/api_controller.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
defmodule AppWeb.ApiController do
use AppWeb, :controller
alias App.Todo
import Ecto.Changeset

def create(conn, params) do

case Todo.create_item(params) do

# Successfully creates item
{:ok, item} ->
json(conn, item)

# Error creating item
{:error, %Ecto.Changeset{} = changeset} ->
errors = traverse_errors(changeset, fn {msg, opts} ->
Regex.replace(~r"%{(\w+)}", msg, fn _, key ->
opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
end)
end)

json(
conn |> put_status(400),
errors
)
end
end

def edit(conn, params) do
dbg("edit")
conn
end

end
9 changes: 5 additions & 4 deletions lib/app_web/router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ defmodule AppWeb.Router do
resources "/items", ItemController
end

# Other scopes may use custom stacks.
# scope "/api", AppWeb do
# pipe_through :api
# end
scope "/api", AppWeb do
pipe_through :api

resources "items", ApiController, only: [:create, :edit]
end
end

0 comments on commit 478ebf0

Please sign in to comment.