balls/lib/balls_pds/plug/object_plug.ex

39 lines
1.2 KiB
Elixir

defmodule BallsPDS.Plug.ObjectPlug do
import Plug.Conn
alias BallsPDS.Ecto.Schema.Object
def init(opts), do: opts
def call(%Plug.Conn{:method => "GET", :request_path => request_path} = conn, _opts) do
with {:acl, false} <- {:acl, is_acl_get?(conn)},
{:object, %Object{} = object} <- {:object, Object.get_by_path(request_path)} do
conn |> assign(:object, object)
else
{:acl, true} ->
conn
{:object, nil} ->
send_resp(conn, 404, "Not found") |> halt()
end
end
def call(%Plug.Conn{:method => "POST", :request_path => request_path} = conn, _opts) do
with {:object, %Object{} = object} <-
{:object, Object.get_by_path(request_path)} do
conn |> assign(:object, object) |> assign(:object_params, %{})
else
{:object, nil} ->
conn |> assign(:object, %Object{}) |> assign(:object_params, %{path: request_path})
end
end
def call(conn, _opts) do
conn |> send_resp(405, "Get out") |> halt()
end
def is_acl_get?(%Plug.Conn{:method => "GET", :request_path => request_path}),
do: String.ends_with?(request_path, ".acl.jsonld")
def is_acl_get?(_), do: false
end