2

Given 2 resources:

jsonapi_resources :companies
jsonapi_resources :users

User has_many Companies

default_paginator = :paged

/companies request is paginated and that's what I want. But I also want to disable it for relationship request /users/4/companies. How to do this?

Oleg Antonyan
  • 2,943
  • 3
  • 28
  • 44

1 Answers1

1

The best solution I found will be to override JSONAPI::RequestParser#parse_pagination like this:

class CustomNonePaginator < JSONAPI::Paginator
  def initialize
  end

  def apply(relation, _order_options)
    relation
  end

  def calculate_page_count(record_count)
    record_count
  end
end

class JSONAPI::RequestParser
  def parse_pagination(page)
    if disable_pagination?
      @paginator = CustomNonePaginator.new
    else
      original_parse_pagination(page)
    end
  end

  def disable_pagination?
     # your logic here 
     # request params are available through @params or @context variables 
     # so you get your action, path or any context data 
  end

  def original_parse_pagination(page)
    paginator_name = @resource_klass._paginator
    @paginator = JSONAPI::Paginator.paginator_for(paginator_name).new(page) unless paginator_name == :none
  rescue JSONAPI::Exceptions::Error => e
    @errors.concat(e.errors)
  end

end
Guy Segev
  • 1,757
  • 16
  • 24
  • Thank you for the answer! Unfortunately it doesn't help me with error: ` Started GET "/api/users/1/companies" for 127.0.0.1 at 2017-02-03 06:55:18 +0200 Processing by Api::CompaniesController#get_related_resources as JSON Parameters: {"relationship"=>"companies", "source"=>"api/users", "user_id"=>"1"} Internal Server Error: undefined method `calculate_page_count' for nil:NilClass /home/oleg/.rbenv/versions/2.3.1/lib64/ruby/gems/2.3.0/gems/jsonapi-resources-0.8.3/lib/jsonapi/processor.rb:170:in `show_related_resources'` – Oleg Antonyan Feb 03 '17 at 04:56
  • 1
    @OlegAntonyan you got your error because you are using `top_level_meta_include_page_count=true` configuration. I've edited my answer to support that as well. Try it and let me know. – Guy Segev Feb 03 '17 at 22:35
  • @OlegAntonyan if you find my answer good and correct, I'd happy if you'd mark my answer as accepted :) – Guy Segev Feb 06 '17 at 17:55
  • Sorry for delay. Yes, it seems to work. Thanks! I found this implementation of `disable_pagination?` method to be what I want: `@params[:action] == 'get_related_resources'` – Oleg Antonyan Feb 08 '17 at 03:58