remi / her

Her is an ORM (Object Relational Mapper) that maps REST resources to Ruby objects. It is designed to build applications that are powered by a RESTful API instead of a database.
MIT License
2.05k stars 322 forks source link

Question: Custom action endpoint and parameters? #193

Open stefan-pdx opened 11 years ago

stefan-pdx commented 11 years ago

Hey guys. I'm really stoked to have come across Her. I look forward to helping out a bit in building out new features.

Unfortunately, I'm dealing with an enterprise-y API that isn't entirely REST-ful. There are two challenges that I've come across:

  1. What's the proper way for specifying a custom endpoint for a resource action? The API I'm working with has an items collection located at /items. However, to create a new item, I have to make a POST to /addItems. Is it possible to override an action path to a different URL?
  2. For a lot of the objects I'm working with, I need to include a URL parameter to specify JSON formatting, such as /items/1?f=json. Is the best way to represent this via the resource_path method? I.e., resource_path "items/:id?f=json"?
  3. Additionally, I sometimes need to include a token as a URL parameter with my requests to be configured and maintained by my application containers and application authentication strategy. I've read the docs on being able to set up additional middleware to manage this, but is there a way to assign a default URL parameter for an object to be included on all requests?

Thanks!

davoclavo commented 11 years ago

Hey @slnovak, I'm also wondering about question 1.

About question 2 & 3, you can write a middleware like this (not tested):

based on Faraday docs

# her.rb

class QueryInjector < Faraday::Middleware
  def call(env)
    token = RequestStore.store[:token] # or any method to get your token

    # env[:url] is a URI object
    env[:url].query = "f=json?token=#{token}"

    # You can also change headers 
    # env[:request_headers]['header']
    @app.call(env)
  end
end

Her::API.setup ... do |c|
  c.use QueryInjector
  c.use Faraday::Request::UrlEncoded
  ...
end
davoclavo commented 11 years ago

For question 1, according to the Her docs you can do this

class Item
  ...
  custom_post :addItems
end