Dedupe poll options

This commit is contained in:
tusooa 2023-03-25 23:20:07 -04:00 committed by XxXCertifiedForkliftDriverXxX
parent 79a18f761b
commit 3095251e6c
2 changed files with 37 additions and 4 deletions

View file

@ -144,6 +144,8 @@ def make_poll_data(%{poll: %{options: options, expires_in: expires_in}} = data)
when is_list(options) do when is_list(options) do
limits = Config.get([:instance, :poll_limits]) limits = Config.get([:instance, :poll_limits])
options = options |> Enum.uniq()
with :ok <- validate_poll_expiration(expires_in, limits), with :ok <- validate_poll_expiration(expires_in, limits),
:ok <- validate_poll_options_amount(options, limits), :ok <- validate_poll_options_amount(options, limits),
:ok <- validate_poll_options_length(options, limits) do :ok <- validate_poll_options_length(options, limits) do
@ -179,9 +181,14 @@ def make_poll_data(_data) do
end end
defp validate_poll_options_amount(options, %{max_options: max_options}) do defp validate_poll_options_amount(options, %{max_options: max_options}) do
if Enum.count(options) > max_options do cond do
Enum.count(options) < 2 ->
{:error, "Poll must contain at least 2 options"}
Enum.count(options) > max_options ->
{:error, "Poll can't contain more than #{max_options} options"} {:error, "Poll can't contain more than #{max_options} options"}
else
true ->
:ok :ok
end end
end end

View file

@ -772,6 +772,32 @@ test "scheduled poll", %{conn: conn} do
assert object.data["type"] == "Question" assert object.data["type"] == "Question"
assert length(object.data["oneOf"]) == 3 assert length(object.data["oneOf"]) == 3
end end
test "cannot have only one option", %{conn: conn} do
conn =
conn
|> put_req_header("content-type", "application/json")
|> post("/api/v1/statuses", %{
"status" => "desu~",
"poll" => %{"options" => ["mew"], "expires_in" => 1}
})
%{"error" => error} = json_response_and_validate_schema(conn, 422)
assert error == "Poll must contain at least 2 options"
end
test "cannot have only duplicated options", %{conn: conn} do
conn =
conn
|> put_req_header("content-type", "application/json")
|> post("/api/v1/statuses", %{
"status" => "desu~",
"poll" => %{"options" => ["mew", "mew"], "expires_in" => 1}
})
%{"error" => error} = json_response_and_validate_schema(conn, 422)
assert error == "Poll must contain at least 2 options"
end
end end
test "get a status" do test "get a status" do