balvig/spyke

Support for id key for resource to be declared

sthaha opened this issue · 3 comments

Is there a way for subclass of Spyke::Base to define the name of the unique-key just like ActiveRecord has support for primary_key to be declared per ActiveRecord class?

Suppose, I want to create a mapping for products that has many versions .

url://path/to/products/ returns

{
  "data": [
   {
     "product_id": "prod_1_id",
     "name": "...",
   },
   {
     "product_id": "prod_2_id",
     "name": "..."
   },
  ]
} 

and url://path/to/prod-vers/ returns

{
  "data": [
   {
    "version_id": "version_1_id",
     "product_id": "prod_1_id",
     "name": "...",
   },
   {
    "version_id": "version_2_id",
     "product_id": "prod_1_id",
     "name": "..."
   },
  ]
} 

Here, there is no easy way to write a json parser that would convert the <resource>_id (product_id, version_id) to id key.

  1. Does the framework already provide a way to handle this?
  2. An idea I had in mind was to allow something like this
class Product < Spyke::Base
   id_key :product_id
   has_many :product_versions
end

class ProductVersion < Spyke::Base
   id_key version_id
   url  "/prd-vers/(:#{id_key})"
   belongs_to :product   
end

Hey there @sthaha!

Currently there is no direct support for that, the primary key is hardcoded as id:

where(id: id).find_one || raise(ResourceNotFound)

Making it configurable seems like a good idea? Maybe could use the same syntax as ActiveRecord: http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/PrimaryKey/ClassMethods.html#method-i-primary_key

@balvig thanks for confirming this. I will work on submitting a PR for this. How soon after the PR merge would you be able to make a release?

@sthaha I've wrapped up the changes in ea0969e and released version 4.1.0

Hope it works for you, thanks so much for your contribution! 🙏