ecto_shorts
ecto_shorts copied to clipboard
feat: enables users to add custom query filters
Overview
Added the EctoShorts.QueryBuilder.Custom behavior. This module enables the addition of custom query filters to the query builder through a custom module defined in the configuration of the dependent application.
Example
An example of how custom filters can be implemented using the EctoShorts.QueryBuilder.Custom
behavior.
This module offers the following features:
- Defines custom filters such as
:select_balance_field_only
,:currency_code
, and:amount_gte
. - Implements the
create_custom_schema_filter/2
function to build queries based on custom filter types.
defmodule MyApp.EctoShorts.QueryBuilder.Custom do
import Ecto.Query, only: [select: 3, where: 3]
alias EctoShorts.QueryBuilder.Custom
@behaviour Custom
@custom_filters [:select_balance_field_only, :currency_code, :amount_gte]
@impl Custom
def custom_filters, do: @custom_filters
@impl Custom
def create_custom_schema_filter({:select_balance_field_only, true}, query),
do: select(query, [b], b.balance)
def create_custom_schema_filter({:select_balance_field_only, _}, query), do: query
@impl Custom
def create_custom_schema_filter({:currency_code, val}, query) do
where(query, [b], fragment("(?).currency_code = ?", b.balance, ^to_string(val)))
end
@impl Custom
def create_custom_schema_filter({:amount_gte, val}, query) do
where(query, [b], fragment("(?).amount >= ?", b.balance, ^val))
end
end