Skip to content

Commit

Permalink
Require ID for PATCH
Browse files Browse the repository at this point in the history
  • Loading branch information
kbaird committed Apr 10, 2019
1 parent d7b446e commit 86d98d9
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
6 changes: 6 additions & 0 deletions lib/jsonapi/error_view.ex
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ defmodule JSONAPI.ErrorView do
|> serialize_error
end

def missing_data_id_param do
"Missing id in data parameter"
|> build_error(400, @crud_message, "/data/id")
|> serialize_error
end

def missing_data_type_param do
"Missing type in data parameter"
|> build_error(400, @crud_message, "/data/type")
Expand Down
4 changes: 4 additions & 0 deletions lib/jsonapi/plugs/format_required.ex
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ defmodule JSONAPI.FormatRequired do

def call(%{params: %{"data" => %{"type" => _, "id" => _}}} = conn, _), do: conn

def call(%{method: "PATCH", params: %{"data" => %{"attributes" => _}}} = conn, _) do
send_error(conn, missing_data_id_param())
end

def call(%{params: %{"data" => %{"attributes" => _}}} = conn, _),
do: send_error(conn, missing_data_type_param())

Expand Down
12 changes: 10 additions & 2 deletions test/jsonapi/plugs/format_required_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,21 @@ defmodule JSONAPI.FormatRequiredTest do
refute conn.halted
end

test "halts if only type member is present on a patch" do
test "halts and returns an error for missing id in data param on a patch" do
conn =
:patch
|> conn("/example", Jason.encode!(%{data: %{type: "something"}}))
|> conn("/example", Jason.encode!(%{data: %{attributes: %{}, type: "something"}}))
|> call_plug

assert conn.halted
assert 400 == conn.status

%{"errors" => [error]} = Jason.decode!(conn.resp_body)

assert %{
"source" => %{"pointer" => "/data/id"},
"title" => "Missing id in data parameter"
} = error
end

test "does not halt if type and id members are present on a patch" do
Expand Down

0 comments on commit 86d98d9

Please sign in to comment.