Flop v0.2.0 Flop.Schema protocol View Source
This protocol allows you to define the sortable and filterable fields in your Ecto schemas.
Usage
Derive Flop.Schema
in your Ecto schema.
defmodule Pet do
use Ecto.Schema
@derive {Flop.Schema,
filterable: [:name, :species], sortable: [:name, :age]}
schema "pets" do
field :name, :string
field :age, :integer
field :species, :string
field :social_security_number, :string
end
end
After that, you can pass the module as the :for
option to Flop.validate/2
.
iex> Flop.validate(%Flop{order_by: [:name]}, for: Pet)
{:ok,
%Flop{
filters: [],
limit: nil,
offset: nil,
order_by: [:name],
order_directions: nil,
page: nil,
page_size: nil
}}
iex> {:error, changeset} = Flop.validate(
...> %Flop{order_by: [:social_security_number]}, for: Pet
...> )
iex> changeset.valid?
false
iex> changeset.errors
[
order_by: {"has an invalid entry",
[validation: :subset, enum: [:name, :age, :species]]}
]
Defining a maximum limit
To define a maximum limit, you can set the max_limit
option when deriving
Flop.Schema
. The limit will be validated accordingly by Flop.validate/1
.
@derive {Flop.Schema,
filterable: [:name, :species],
sortable: [:name, :age],
max_limit: 100}
Link to this section Summary
Functions
Returns the filterable fields of a schema.
Returns the maximum limit of a schema.
Returns the sortable fields of a schema.
Link to this section Types
Specs
t() :: term()
Link to this section Functions
Specs
Returns the filterable fields of a schema.
iex> Flop.Schema.filterable(%Pet{})
[:name, :species]
Specs
max_limit(any()) :: pos_integer() | nil
Returns the maximum limit of a schema.
iex> Flop.Schema.max_limit(%Pet{})
20
Specs
Returns the sortable fields of a schema.
iex> Flop.Schema.sortable(%Pet{})
[:name, :age, :species]