How to define custom sort?

I'm trying to get started with Ash but I'm really struggling with the basics. I'm trying to do something like this:
defmodule MyResource do
use Ash.Resource, data_layer: AshPostgres.DataLayer

actions do
read :custom_sort do
argument :sort, :atom do
constraints [one_of: [:newest, :oldest]]
allow_nil? false
end

build(sort: [inserted_at: expr(^arg(:sort) == :newest do :asc else :desc end)])
end
end
end
defmodule MyResource do
use Ash.Resource, data_layer: AshPostgres.DataLayer

actions do
read :custom_sort do
argument :sort, :atom do
constraints [one_of: [:newest, :oldest]]
allow_nil? false
end

build(sort: [inserted_at: expr(^arg(:sort) == :newest do :asc else :desc end)])
end
end
end
but this doesnt work. Nevermind if it makes sense. I'm really just trying to find out how I can supply an argument to an action and do something with it. I have looked through the docs to no avail. The docs on expr don't deal with conditions and also apparently args can't be used in sort which is also not covered in the docs, so I'm really lost. Any help would be appreciated.
2 Replies
barnabasj
barnabasj2y ago
in this case you would probably do a custom preparation like this
defmodule MyResource do
use Ash.Resource, data_layer: AshPostgres.DataLayer

actions do
read :custom_sort do
argument :sort, :atom do
constraints [one_of: [:newest, :oldest]]
allow_nil? false
end

prepare fn query, _ ->
query
|> Ash.Query.sort(
[inserted_at: if Ash.Query.get_argument(query, :sort) == :newest do :asc else :desc end]
)
end
end
end
defmodule MyResource do
use Ash.Resource, data_layer: AshPostgres.DataLayer

actions do
read :custom_sort do
argument :sort, :atom do
constraints [one_of: [:newest, :oldest]]
allow_nil? false
end

prepare fn query, _ ->
query
|> Ash.Query.sort(
[inserted_at: if Ash.Query.get_argument(query, :sort) == :newest do :asc else :desc end]
)
end
end
end
also you need to put prepare before build e.g. prepare build(:sort, [intereset_at: :asc])
Nefcairon
Nefcairon2y ago
Please do not post here anymore. This channel is archived. Please post in the official elixir forum.

Did you find this page helpful?