Skip to content

Commit

Permalink
implement POST endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexandruBurlacu committed Sep 24, 2017
1 parent cb2e521 commit d02c6ec
Showing 1 changed file with 33 additions and 10 deletions.
43 changes: 33 additions & 10 deletions lib/task_router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,47 +5,70 @@ defmodule ElixirDocker.Router.TasksRouter do
"""

use Plug.Router
require Logger

alias ElixirDocker.Record
alias ElixirDocker.Repo

plug :match
plug Plug.Parsers, parsers: [:json],
pass: ["application/json"],
json_decoder: Poison
plug :dispatch

defp common_behaviour(connection, data) do
defp response(connection, code, data) do
connection
|> put_resp_content_type("application/json")
|> send_resp(200, Poison.encode!(data))
|> send_resp(code, Poison.encode!(data))
end

defp valid_data?(data) do
["title", "description", "due_date", "priority"]
|> Enum.map(fn k ->
data
|> Map.has_key?(k)
end)
|> Enum.all?
end

post "/" do
conn
|> common_behaviour(%{info: "Welcome from post",
data: conn.body_params})
data = conn.body_params

if (valid_data?(data)) do

record = %Record{title: data["title"],
description: data["description"],
due_date: Date.from_iso8601!(data["due_date"]),
priority: data["priority"]}

resp = Repo.insert! record

conn |> response(201, %{info: "Task created", task_id: resp.id})
else
conn |> response(400, %{info: "Invalid body"})
end
end

get "/" do
conn
|> common_behaviour(%{info: "Welcome from listing",
|> response(200, %{info: "Welcome from listing",
data: [%{no: "posts"}, %{no: "posts"}]})
end

get "/:id" do
conn
|> common_behaviour(%{info: "Welcome from details",
|> response(200, %{info: "Welcome from details",
data: %{no: "info on #{id}"}})
end

put "/:id" do
conn
|> common_behaviour(%{info: "Welcome from update",
|> response(200, %{info: "Welcome from update",
data: %{no: "way to update #{id}"}})
end

delete "/:id" do
conn
|> common_behaviour(%{info: "Welcome from delete",
|> response(200, %{info: "Welcome from delete",
data: %{no: "way to delete #{id}"}})
end
end

0 comments on commit d02c6ec

Please sign in to comment.