Canary.Utils (canary v2.0.0-dev)
Common utils functions for Canary.Plugs
and Canary.Hooks
Summary
Functions
Check if an action is valid based on the options.
Apply the error handler to the connection or socket
Check if the not_found handler should be applied for given action, assigns and options
Get the resource id from the connection params
Get the resource name from the options, covert it to atom and pluralize it if needed - only for :index action.
Returns the :non_id_actions option if it is present
Preload associations if needed
Check if a key is present in a keyword list
Functions
Check if an action is valid based on the options.
iex> Canary.Utils.action_valid?(:index, only: [:index, :show])
true
iex> Canary.Utils.action_valid?(:index, except: :index)
false
iex> Canary.Utils.action_valid?(:show, except: :index, only: :show)
** (ArgumentError) You can't use both :except and :only options
@spec apply_error_handler(Plug.Conn.t(), atom(), Keyword.t()) :: Plug.Conn.t()
@spec apply_error_handler(Phoenix.LiveView.Socket.t(), atom(), Keyword.t()) :: {:halt, Phoenix.LiveView.Socket.t()}
Apply the error handler to the connection or socket
Check if the not_found handler should be applied for given action, assigns and options
@spec get_resource_id(Plug.Conn.t(), Keyword.t()) :: String.t() | nil
@spec get_resource_id(map(), Keyword.t()) :: String.t() | nil
Get the resource id from the connection params
iex> Canary.Utils.get_resource_id(%{"id" => "9"}, [])
"9"
iex> Canary.Utils.get_resource_id(%Plug.Conn{params: %{"custom_id" => "1"}}, id_name: "custom_id")
"1"
iex> Canary.Utils.get_resource_id(%{"user_id" => "7"}, id_name: "user_id")
"7"
iex> Canary.Utils.get_resource_id(%{"other_id" => "9"}, id_name: "id")
nil
Get the resource name from the options, covert it to atom and pluralize it if needed - only for :index action.
If the :as
option is provided, it will be used as the resource name.
iex> Canary.Utils.get_resource_name(:show, model: MyApp.Post)
:post
iex> Canary.Utils.get_resource_name(:index, model: MyApp.Post)
:posts
iex> Canary.Utils.get_resource_name(:index, model: MyApp.Post, as: :my_posts)
:my_posts
Returns the :non_id_actions option if it is present
@spec preload_if_needed(nil, Ecto.Repo.t(), Keyword.t()) :: nil
@spec preload_if_needed([Ecto.Schema.t()], Ecto.Repo.t(), Keyword.t()) :: [ Ecto.Schema.t() ]
Preload associations if needed
Check if a key is present in a keyword list