View Source FatEcto.FatQuery.Sortable behaviour (FatEcto v1.0.0)
Provides functionality to sort Ecto queries based on user-defined rules.
This module allows sorting queries using predefined default fields (handled by FatOrderBy
)
and custom fields (handled by a fallback function).
Usage
defmodule MyApp.SortQuery do
<!-- needed if you are writing queries in override_sortable -->
import Ecto.Query
use FatEcto.FatQuery.Sortable,
sortable_fields: %{"id" => "$asc", "name" => ["$asc", "$desc"]},
overrideable_fields: ["custom_field"]
@impl true
def override_sortable(query, field, operator) do
case {field, operator} do
{"custom_field", "$asc"} ->
from(q in query, order_by: [asc: fragment("?::jsonb->>'custom_field'", q)])
_ ->
query
end
end
end
Example
query = from(u in User)
sort_params = %{"id" => "$asc", "name" => "$desc", "custom_field" => "$asc"}
MyApp.SortQuery.build(query, sort_params)
This will sort the query by id
in ascending order, name
in descending order, and apply custom sorting for custom_field
.
Summary
Callbacks
Callback for handling custom sorting logic.
Callbacks
@callback override_sortable( query :: Ecto.Query.t(), field :: String.t() | atom(), operator :: String.t() ) :: Ecto.Query.t()
Callback for handling custom sorting logic.
This function is called for fields defined in overrideable_fields
. The default behavior is to return the query,
but it can be overridden by the using module.