Pagination is not working for related resources

I have two resources. The two are related to each other.

Article resource

defmodule Accounts.Blog.Article do
  use Ash.Resource,
    domain: Account.Domain,
    data_layer: AshPostgres.DataLayer,
    extensions: [AshJsonApi.Resource]

  ...
  
actions do
    read :read do  
      pagination countable: true, offset?: true, required?: true, default_limit: 10
    end
  end

  relationships do
    has_many :comments, Comment
  end
end

Comments resource

defmodule Accounts.Blog.Comment do
  use Ash.Resource,
    domain: Account.Domain,
    data_layer: AshPostgres.DataLayer,
    extensions: [AshJsonApi.Resource]

  ...
  
  actions do
   read :read do  
      pagination countable: true, offset?: true, required?: true, default_limit: 10
   end
  end

  relationships do
    belongs_to, :article, Article
  end
end

Domain

defmodule Account.Domain do
  use Ash.Domain, extensions: [AshJsonApi.Domain]

  alias Accounts.Blog.{Article, Comment}
  
  json_api do
    routes do
      base_route "/articles", Article do
        get :read
        related :comments, :read
      end
    end
  end
end

When I try to get the related comments for Accounts.Blog.Article using the endpoint articles/:article_id/comments, the records are not paginated as expected. However, if I make a GET request to /articles, the articles are paginated as expected. Fetching the resource directly works, but pagination does not work for the related resource.

I don’t think pagination is implemented for relationship routes like that, but you can do this in your other resource:

routes do
  index "/articles/:article_id/comments", :read
end

...

actions do
  read :read do
    argument :article_id, :uuid

    prepare fn query, _ -> 
      case Ash.Query.fetch_argument(query, :article_id) do
        {:ok, article_id} -> Ash.Query.filter(query, article_id == ^article_id)
        :error -> query
      end
    end
  end  
end

Could you open a request against ash_json_api to implement pagination for related routes? For backwards compatibility it would have to default to false, but we could add related :comments, :read, paginate?: true to make it obey the pagination rules of the destination action.

2 Likes

Thank you for replying. I have opened a request on ash_jsob_api.

Issue: Implement pagination feature for related routes · Issue #230 · ash-project/ash_json_api · GitHub

1 Like