balvig / spyke

Interact with REST services in an ActiveRecord-like manner
MIT License
902 stars 66 forks source link

Associations through nested JSON response #149

Open srozen opened 11 months ago

srozen commented 11 months ago

Hello, is there a way to make the association definition to pick up nested resources from the JSON payload?

Let's say we have a Shop model with Articles and Employees, but the JSON payload when fetching the Shop is the following :

{ 
  "id": 1,
  "resources": {
    "employees": [],
    "articles": [],
  }
}

How could one define the has_many such that shop.employees returns the Spyke association?

balvig commented 11 months ago

@srozen there is!

...unfortunately it expects the JSON to appear in a certain way though, ie:

{ 
  "id": 1,
  "employees": [],
  "articles": [],
}

...so in your example a bit of a workaround may be required. 🤔

You could either massage the incoming JSON in Faraday before passing it on to Spyke to fit the format above, or perhaps use a class to join them together:

class Book < Spyke::Base
  has_one :resources, class_name: "BookResources", uri: nil
end

class BookResources < Spyke::Base
  has_many :employees, uri: nil
  has_many :articles, uri: nil
end

book.resources.employees # => []
book.resources.articles # => []