Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conditionally add base_query/1 and finalize_query/2 callbacks via macro #21

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 3 additions & 34 deletions lib/live_view.ex
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,10 @@ defmodule Permit.Phoenix.LiveView do
alias PermitPhoenix.RecordNotFoundError

import Phoenix.LiveView
import PermitPhoenix.Macros

permit_ecto_callbacks()
@callback resource_module() :: module()
if :ok == Application.ensure_loaded(:permit_ecto) do
@callback base_query(Types.resolution_context()) :: Ecto.Query.t()
@callback finalize_query(Ecto.Query.t(), Types.resolution_context()) :: Ecto.Query.t()
end

@callback handle_unauthorized(Types.action_group(), PhoenixTypes.socket()) ::
PhoenixTypes.hook_outcome()
Expand Down Expand Up @@ -157,8 +155,7 @@ defmodule Permit.Phoenix.LiveView do
end

@impl true
def finalize_query(query, resolution_context),
do: unquote(__MODULE__).finalize_query(query, resolution_context, unquote(opts))
def finalize_query(query, %{}), do: query
end

@impl true
Expand Down Expand Up @@ -287,34 +284,6 @@ defmodule Permit.Phoenix.LiveView do
end
end

if :ok == Application.ensure_loaded(:permit_ecto) do
@doc false
def base_query(
%{
action: action,
resource_module: resource_module,
socket: socket,
params: params
},
opts
) do
param = __MODULE__.id_param_name(action, socket, opts)
field = __MODULE__.id_struct_field_name(action, socket, opts)

case params do
%{^param => id} ->
resource_module
|> Permit.Ecto.filter_by_field(field, id)

_ ->
Permit.Ecto.from(resource_module)
end
end

@doc false
def finalize_query(query, %{}, _opts), do: query
end

@doc false
def loader(resolution_context, opts) do
case opts[:loader] do
Expand Down
13 changes: 13 additions & 0 deletions lib/permit_phoenix/macros.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
defmodule PermitPhoenix.Macros do
@moduledoc false

defmacro permit_ecto_callbacks do
if :ok == Application.ensure_loaded(:permit_ecto) do
quote do
@callback base_query(Permit.Types.resolution_context()) :: Ecto.Query.t()
@callback finalize_query(Ecto.Query.t(), Permit.Types.resolution_context()) ::
Ecto.Query.t()
end
end
end
end