JsonApiClient / json_api_client

Build client libraries compliant with specification defined by jsonapi.org
MIT License
361 stars 186 forks source link

`has_many` associations return an `Array` instead of a `ResultSet`. #270

Closed jimsynz closed 5 years ago

jimsynz commented 7 years ago

Our upstream server is a jsonapi_resources based server which is set to paginate at 20 records by default. When we attempted to load relationships using json_api_client's has_many macros it would return an Array containing exactly 20 records, and not a ResultSet so we were unable to access the request metadata to load additional records.

Example:

[1] pry(main)> pf = FairfaxApiClient::ProductFeed.find("3d9ec6c2-2ba3-4a5b-8037-298b9f3f806e").first
I, [2017-08-21T11:45:22.741440 #56703]  INFO -- : [localhost] GET /pim/product_feeds/3d9ec6c2-2ba3-4a5b-8037-298b9f3f806e (0.068 s)
=> #<FairfaxApiClient::ProductFeed:@attributes={"id"=>"3d9ec6c2-2ba3-4a5b-8037-298b9f3f806e", "meta"=>{"matching_products"=>146, "matching_categories"=>18, "matching_vendors"=>11}, "type"=>"product_feeds", "name"=>"Fruit"}>
[2] pry(main)> v = pf.vendors; puts "#{v.class}; #{v.size}"
I, [2017-08-21T11:46:08.534553 #56703]  INFO -- : [localhost] GET /pim/product_feeds/3d9ec6c2-2ba3-4a5b-8037-298b9f3f806e/vendors (0.080 s)
Array; 20
=> nil

Whereas by duck punching JsonApiClient::Associations::BaseAssociation#from_result_set to not call #to_a on the result set makes the response work as expected:

[3] pry(main)> JsonApiClient::Associations::BaseAssociation.class_eval { def from_result_set(result_set); result_set; end }
=> :from_result_set
[4] pry(main)> pf = FairfaxApiClient::ProductFeed.find("3d9ec6c2-2ba3-4a5b-8037-298b9f3f806e").first
I, [2017-08-21T11:49:33.598500 #56703]  INFO -- : [localhost] GET /pim/product_feeds/3d9ec6c2-2ba3-4a5b-8037-298b9f3f806e (0.067 s)
=> #<FairfaxApiClient::ProductFeed:@attributes={"id"=>"3d9ec6c2-2ba3-4a5b-8037-298b9f3f806e", "meta"=>{"matching_products"=>146, "matching_categories"=>18, "matching_vendors"=>11}, "type"=>"product_feeds", "name"=>"Fruit"}>
[5] pry(main)> v = pf.vendors; puts "#{v.class}; #{v.meta["record_count"]}"
I, [2017-08-21T11:50:22.216745 #56703]  INFO -- : [localhost] GET /pim/product_feeds/3d9ec6c2-2ba3-4a5b-8037-298b9f3f806e/vendors (0.056 s)
JsonApiClient::ResultSet; 28
=> nil

The array-casting step looks like it was added for a reason, so I'd like to double check that removing it doesn't cause any unexpected failures. If so then I'll happily prepare a pull request to fix it.

webandtech commented 7 years ago

👍 running into this as well

gaorlov commented 5 years ago

This looks resolved. Let's reopen it if the issue comes up again.

risc12 commented 4 years ago

@gaorlov This still seems to be the case, although @jimsynz's "hack" seems to do the trick.