plug_indie/lib/response.ex
2024-11-29 10:42:27 +01:00

38 lines
1 KiB
Elixir

defmodule PlugIndie.Response do
import Plug.Conn
def send_content(conn, content) do
json_encoder = conn.private[:plug_micropub][:json_encoder]
body = json_encoder.encode!(content)
conn
|> put_resp_content_type("application/json")
|> send_resp(:ok, body)
end
def send_error(conn, {:error, error}) do
body = %{error: error}
_send_error(conn, body)
end
def send_error(conn, {:error, error, description}) do
body = %{error: error, error_description: description}
_send_error(conn, body)
end
defp _send_error(conn, body) do
json_encoder = conn.private[:plug_micropub][:json_encoder]
code = get_error_code(body.error)
body = json_encoder.encode!(body)
conn
|> put_resp_content_type("application/json")
|> send_resp(code, body)
end
defp get_error_code(:insufficient_scope), do: :unauthorized
defp get_error_code(:invalid_request), do: :bad_request
defp get_error_code(:request_error), do: :internal_server_error
defp get_error_code(code), do: code
end