json_api_client icon indicating copy to clipboard operation
json_api_client copied to clipboard

current_page is kind of incorrect as per the json_api standard

Open garytaylor opened this issue 9 years ago • 3 comments

If you look at paginating/paginator.rb line 55

      def current_page
        params.fetch("page", 1).to_i
      end

This is saying that params["page"] is expected to be convertable into an integer. However, the json_api specification says the following :-

Note: JSON API is agnostic about the pagination strategy used by a server. Effective pagination strategies include (but are not limited to): page-based, offset-based, and cursor-based. The page query parameter can be used as a basis for any of these strategies. For example, a page-based strategy might use query parameters such as page[number] and page[size], an offset-based strategy might use page[offset] and page[limit], while a cursor-based strategy might use page[cursor].

I guess this should be configurable as it is implementation specific ?

Thanks

Gary

garytaylor avatar Dec 08 '15 11:12 garytaylor

Yeah, the spec doesn't say how the server should implement the pagination, so I made the paginator customizable (with a "sensible" default). See. https://github.com/chingor13/json_api_client#custom-paginator

Most of the handlers are customizable in case you want to deviate from the spec - you just have to plug in whatever handler you want.

chingor13 avatar Dec 14 '15 17:12 chingor13

A custom one that works with hashes would look like. The size alias is so that it works with active model serializers

class MyPaginator < JsonApiClient::Paginating::Paginator

  alias_method :size, :per_page

  def total_pages
    if links["last"]
      last_params = params_for_uri(links["last"])
      last_params.fetch("page[number]") do
        current_page
      end.to_i
    else
      current_page
    end
  end

  def per_page
    params.fetch("page[size]") do
      result_set.length
    end.to_i
  end

  def current_page
    params.fetch("page[number]", 1).to_i
  end

end

jsamos avatar Apr 11 '16 22:04 jsamos

I would consider adding this info to the README or something. I just spent pretty much 2 days trying to debug why pages.total_pages was constantly giving me 1 even though the last link had a page[number] of 25.

I know the README says you can customize this and how to do so, but it should probably indicate somewhere that you probably will have to do this as most all server side JSONAPI implementations I've looked into implement the 'page[number]' approach.

dmbrooking avatar May 19 '16 18:05 dmbrooking