FlopRest.Filters (FlopRest v0.6.1)

Copy Markdown View Source

Extracts and transforms REST-style filter params to Flop format and vice versa.

Summary

Functions

Extracts filters from params map.

Extracts filters from params map, optionally filtering by a set of allowed fields.

Converts a list of Flop.Filter structs back to REST-style params.

Functions

extract(params)

@spec extract(map()) :: [map()]

Extracts filters from params map.

Handles:

  • Bare values: status=published{field: status, op: ==, value: published}
  • Operators: amount[gte]=10{field: amount, op: >=, value: 10}
  • Comma-separated lists: status[in]=draft,published
  • Bracket-style lists: status[in][]=draft&status[in][]=published
  • Multiple ops on same field: amount[gte]=10&amount[lte]=100 → two filters

List operators (in, not_in, like_and, like_or, ilike_and, ilike_or) automatically split comma-separated string values into lists. A single value (no commas) is passed through as a string, allowing Flop to apply its own parsing (e.g. whitespace splitting for like_and). Use the bracket [] syntax if values themselves contain commas.

Unknown operators are passed through verbatim for Flop to validate.

extract(params, filterable)

@spec extract(map(), MapSet.t(String.t()) | nil) :: {[map()], map()}

Extracts filters from params map, optionally filtering by a set of allowed fields.

When filterable is provided, only fields in the set become filters. Other params are returned as the second element of the tuple.

Parameters

  • params - The params map to extract filters from
  • filterable - A MapSet of string field names that are allowed as filters, or nil to allow all fields

Returns

A tuple of {filters, extra_params} where:

  • filters - List of filter maps for filterable fields
  • extra_params - Map of params that weren't converted to filters

Examples

iex> FlopRest.Filters.extract(%{"name" => "Fido", "custom" => "value"}, MapSet.new(["name"]))
{[%{"field" => "name", "op" => "==", "value" => "Fido"}], %{"custom" => "value"}}

to_rest(filters)

@spec to_rest([Flop.Filter.t()] | nil) :: map()

Converts a list of Flop.Filter structs back to REST-style params.

Equality filters (:==) become bare key-value params. Other operators become nested params like field[operator].

Examples

iex> FlopRest.Filters.to_rest([%Flop.Filter{field: :status, op: :==, value: "active"}])
%{"status" => "active"}

iex> FlopRest.Filters.to_rest([%Flop.Filter{field: :amount, op: :>=, value: 100}])
%{"amount[gte]" => 100}

iex> FlopRest.Filters.to_rest([])
%{}

iex> FlopRest.Filters.to_rest(nil)
%{}