Skip to content

Commit 08f31a7

Browse files
committed
Refactor image upload handling in PostController
- Simplified the image upload logic using a `with` statement for better readability. - Updated error handling to return a 404 response when the post is not found, instead of a 400 response. - Added a test case to verify that a 404 response is returned when attempting to upload an image for a non-existent post.
1 parent 99a3979 commit 08f31a7

File tree

2 files changed

+42
-16
lines changed

2 files changed

+42
-16
lines changed

lib/literature/controllers/post_controller.ex

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,27 +2,29 @@ defmodule Literature.PostController do
22
use Literature.Web, :controller
33

44
def upload_image(conn, %{"image" => image} = params) do
5-
params
6-
|> get_post()
7-
|> Literature.update_post(%{"upload_image" => rename_filename(image)})
8-
|> case do
9-
{:ok, post} ->
5+
with %Literature.Post{} = post <- get_post(params),
6+
{:ok, post} <- Literature.update_post(post, %{"upload_image" => rename_filename(image)}) do
7+
conn
8+
|> put_resp_content_type("application/json")
9+
|> send_resp(
10+
200,
11+
Jason.encode!(%{
12+
success: 1,
13+
file: %{
14+
url: literature_image_url(post, :upload_image)
15+
}
16+
})
17+
)
18+
else
19+
{:error, %Ecto.Changeset{}} ->
1020
conn
1121
|> put_resp_content_type("application/json")
12-
|> send_resp(
13-
200,
14-
Jason.encode!(%{
15-
success: 1,
16-
file: %{
17-
url: literature_image_url(post, :upload_image)
18-
}
19-
})
20-
)
22+
|> send_resp(400, Jason.encode!(%{success: 0}))
2123

22-
{:error, %Ecto.Changeset{}} ->
24+
nil ->
2325
conn
2426
|> put_resp_content_type("application/json")
25-
|> send_resp(400, Jason.encode!(%{success: 0}))
27+
|> send_resp(404, Jason.encode!(%{success: 0, error: "Post not found"}))
2628
end
2729
end
2830

test/literature/controllers/post_controller_test.exs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,4 +60,28 @@ defmodule Literature.PostControllerTest do
6060
"success" => 1
6161
}
6262
end
63+
64+
test "upload image returns 404 when post does not exist",
65+
%{conn: conn, publication: publication} do
66+
params = %{image: file_upload_image()}
67+
68+
conn =
69+
post(
70+
conn,
71+
Routes.literature_dashboard_path(
72+
conn,
73+
:upload_image,
74+
publication.slug,
75+
"non-existent-slug",
76+
[
77+
"upload-image"
78+
]
79+
),
80+
params
81+
)
82+
83+
response = json_response(conn, 404)
84+
85+
assert response == %{"success" => 0, "error" => "Post not found"}
86+
end
6387
end

0 commit comments

Comments
 (0)