View Source EctoJuno.Query.Sorting (ecto_juno v0.1.0)

Module for sorting base query

Link to this section Summary

Link to this section Functions

Link to this function

sort_query(query, schema_or_allowed_fields, params)

View Source
@spec sort_query(any(), atom() | list(), map()) :: Ecto.Query.t()

Sorts query

### Parameters

  • query: the query you want to sort
  • schema_or_allowed_fields: must either be the model's Ecto.Schema either list of atom keys
  • params: map that can have sort_by, sort_direction fields with string values

### Usage

  defmodule Sample.Accounts do
    alias EctoJuno.Query.Sorting
    alias Sample.Accounts.User
    alias Sample.Repo

    def sort_users(sort_by, sort_direction) do
      User
      |> Sorting.sort_query(User, %{"sort_by" => sort_by, "sort_direction" => sort_direction})
      |> Repo.all()
    end
  end

You can also pass sort_by and sort_direction as atom keys

#### Invoking sort_query/2

    Sorting.sort_query(query, User)

In such case sorting params will be extracted from configuration if exist. If not than default sorting: ascending by inserted_at field will be applied