Ash FrameworkAF
Ash Framework3y ago
4 replies
laznic

How to filter results when using keyset pagination?

After a lot of trial and error, I managed to get the next page for the keyset pagination in my project by using something like
next_page = MyApp.ResourceApi.page(
  socket.assigns.items,
  :next
)

This works perfectly fine, however I also have filters the user could apply to the items list. I got one solution working, however I'm not sure if it's the "proper" way to do it. I'm wondering if there would be a more cleaner solution to do it?

My current solution is based on the small Filters guide in the Ash Documentation:

last_item = List.last(
  socket.assigns.items.results
)

next_page = MyApp.ResourceApi.Resource.filter!(
  filter_values.search,
  filter_values.status,
  page: [
    limit: 16, 
    after: last_item.__metadata__.keyset
  ]
)

# Resource actions
  actions do
    read :filter do
      argument :name, :string
      argument :status, {:array, :string}

      prepare build(sort: [id: :desc])
      pagination countable: :by_default, keyset?: true, default_limit: 16

      filter expr(
        ilike(name, "%" <> ^arg(:name) <> "%")
        and type(status, :string) in ^arg(:status)
      )
    end
  end
Was this page helpful?