Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
defmodule TasksAppWeb.TodoController do
use TasksAppWeb, :controller
use Plug.ErrorHandler
alias TasksApp.Todos
alias TasksApp.Todos.Todo
def index(conn, _params) do
todos = Todos.list_todos()
conn
|> json(todos)
end
def create(conn, %{"todo" => todo_params}) do
with {:ok, %Todo{} = todo} <- Todos.create_todo(todo_params) do
conn
|> put_status(:created)
|> put_resp_header("location", Routes.todo_path(conn, :show, todo))
|> json(todo)
end
end
def show(conn, %{"id" => id}) do
todo = Todos.get_todo!(id)
conn
|> json(todo)
end
def update(conn, %{"id" => id, "todo" => todo_params}) do
todo = Todos.get_todo!(id)
with {:ok, %Todo{} = todo} <- Todos.update_todo(todo, todo_params) do
conn
|> json(todo)
end
end
def delete(conn, %{"id" => id}) do
todo = Todos.get_todo!(id)
with {:ok, %Todo{}} <- Todos.delete_todo(todo) do
conn
|> send_resp(:no_content, "")
end
end
def handle_errors(conn, %{kind: _kind, reason: reason, stack: _stack}) do
case reason do
%Ecto.NoResultsError{} -> conn |> send_resp(:not_found, "")
_ -> conn |> send_resp(:internal_server_error, "")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.