MastodonAPI: Support idempotency key.

This commit is contained in:
lain 2018-05-04 20:30:29 +02:00
parent 5b6d6d7f2d
commit fcd3eca167
2 changed files with 32 additions and 3 deletions

View File

@ -275,7 +275,19 @@ def post_status(%{assigns: %{user: user}} = conn, %{"status" => _} = params) do
|> Map.put("in_reply_to_status_id", params["in_reply_to_id"]) |> Map.put("in_reply_to_status_id", params["in_reply_to_id"])
|> Map.put("no_attachment_links", true) |> Map.put("no_attachment_links", true)
{:ok, activity} = CommonAPI.post(user, params) idempotency_key =
case get_req_header(conn, "idempotency-key") do
[key] -> key
_ -> Ecto.UUID.generate()
end
{:ok, activity} =
Cachex.get!(
:user_cache,
"idem:#{idempotency_key}",
fallback: fn _ -> CommonAPI.post(user, params) end
)
render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}) render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
end end

View File

@ -63,9 +63,12 @@ test "the public timeline", %{conn: conn} do
test "posting a status", %{conn: conn} do test "posting a status", %{conn: conn} do
user = insert(:user) user = insert(:user)
conn = idempotency_key = "Pikachu rocks!"
conn_one =
conn conn
|> assign(:user, user) |> assign(:user, user)
|> put_req_header("idempotency-key", idempotency_key)
|> post("/api/v1/statuses", %{ |> post("/api/v1/statuses", %{
"status" => "cofe", "status" => "cofe",
"spoiler_text" => "2hu", "spoiler_text" => "2hu",
@ -73,9 +76,23 @@ test "posting a status", %{conn: conn} do
}) })
assert %{"content" => "cofe", "id" => id, "spoiler_text" => "2hu", "sensitive" => false} = assert %{"content" => "cofe", "id" => id, "spoiler_text" => "2hu", "sensitive" => false} =
json_response(conn, 200) json_response(conn_one, 200)
assert Repo.get(Activity, id) assert Repo.get(Activity, id)
conn_two =
conn
|> assign(:user, user)
|> put_req_header("idempotency-key", idempotency_key)
|> post("/api/v1/statuses", %{
"status" => "cofe",
"spoiler_text" => "2hu",
"sensitive" => "false"
})
assert %{"id" => second_id} = json_response(conn_two, 200)
assert id == second_id
end end
test "posting a sensitive status", %{conn: conn} do test "posting a sensitive status", %{conn: conn} do